簡體   English   中英

如何從另一個類設置UILabel文本

[英]How to set UILabel text from another class

我對UILabel有問題。 這是兩個文件的ViewControllerMainClass第一個是帶有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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM