Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
914 views
in Technique[技术] by (71.8m points)

iphone - Setting label text in another class

In my viewcontroller, I am creating a label here.

In another viewcontroller I am creating an instance of the first view controller. Here I tried setting the text property of the label. But it doesn't work. I have checked my code over and over and couldn't find any anything missing. I tried creating the label both programmatically as well as using interface builder. Still cant set the text property of the label. Any reason for this?

I create the label in

- (void)viewDidLoad
{
myLabel = [[UILabel alloc]init];
[myLabel setText:@"Hi"];
[myLabel1 setText:@"Hello"];
 [myLabel setFrame:CGRectMake(105, 130, 120, 30)];
 [myLabel setBackgroundColor:[UIColor clearColor]];
 [myLabel setTextColor:[UIColor whiteColor]];
 [myLabel setTextAlignment:UITextAlignmentCenter];
 [myLabel setAdjustsFontSizeToFitWidth:YES];
 [self.view addSubview:myLabel];
 [myLabel release];
}

In my first view controller

MySecondViewcontroller *showMyViewcontroller = [[ MySecondViewcontroller    alloc]initWithNibName:@"MySecondViewcontroller" bundle:nil];;
showMyViewcontroller.myLabel = @"I cant set the text";
[self.navigationcontroller pushViewController: showMyViewcontroller animated:YES];
[showMyViewcontroller release];

What I am doing wrong here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try using an intermediate string to do it, like so:

In FirstViewController:

- (void)loadNextView {
    // load your view
    SecondViewController *vc = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];

    // set a string in your second view (NOT a label)
    vc.myString = @"Some String";

    // push it or whatever
    [self.navigaitonController pushViewController:vc animated:YES];
    [vc release];
}

In your SecondViewController.h

@interface SecondViewController : UIViewController {
    UILabel *myLabel;
    NSString *myString;
}

@property (nonatomic, retain) UILabel *myLabel;
@property (nonatomic, retain) NSString *myString;

In your SecondViewController.m

- (void)viewDidLoad {
    // view is now loaded, so we can set the label:
    myLabel.text = myString;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...