[英]How to set UILabel text from another class
我對UILabel
有問題。 這是兩個文件的ViewController
和MainClass
第一個是帶有label1
插座的nib文件的控制器。 第二個文件是帶有另一個標簽mainLabel
的類,該標簽包含文本(“從MainClass的init方法設置”)。 我想在ViewController
中將mainLabel
設置為label1
。
在MainClass的init
方法中,我為mainLabel.text
設置了文本
mainLabel.text = @"Set from init method in MainClass";
然后我打電話給NSLog(@"%@",mainLabel.text);
但在控制台中,我為空
2011-12-14 10:31:31.048 ClassTask[1076:f803] (null)
然后,我打電話給label1 = newClass.mainLabel;
在- (void)viewDidLoad
中,我的iPhone模擬器中的帶label1
視圖沒有文本。 // ViewController.h
#import <UIKit/UIKit.h>
#import "MainClass.h"
@interface ViewController : UIViewController {
UILabel *label1;
MainClass *newClass;
}
@property (nonatomic, retain) IBOutlet UILabel *testLabel;
@end
// ViewController.m
#import "ViewController.h"
@implementation ViewController
@synthesize label1;
-(void) dealloc{
[label1 release];
[super dealloc];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
newClass = [MainClass new];
label1 = newClass.mainLabel;
}
@end
// MainClass.h
#import <UIKit/UIKit.h>
@interface MainClass : NSObject {
UILabel *mainLabel;
}
@property (nonatomic, retain) IBOutlet UILabel *mainLabel;
@end
// MainClass.m
#import "MainClass.h" @implementation MainClass @synthesize mainLabel;
-(id) init {
if (self = [super init]) {
mainLabel.text = @"Set from init method in MainClass";
NSLog(@"%@",mainLabel.text);
}
return self; }
-(void)dealloc {
[mainLabel release];
[super dealloc];
}
@end
為什么不將其設為NSString,基本上就是要在另一個ViewController中訪問的文本。
我發現的另一個錯誤
#import "ViewController.h"
@implementation ViewController
@synthesize label1;
-(void) dealloc{
[label1 release];
[super dealloc];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
newClass = [MainClass new];
**label1 = newClass.mainLabel.Text; // its a label, so whenever you retrieve its value it would be like labelName.Text**
}
@end
我想,如果您想將此string
[在您的代碼中,將mainLabel.text]從一個控制器傳遞到另一個控制器,則可以使用UISharedApplication
..關注此鏈接。... https: //stackoverflow.com/questions/8486540/ 我想將數據從一個視圖控制器傳遞給另一個控制器/ 8487095#8487095
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.