Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Change UIButton title?

MyViewController has one UIButton and another MainViewController use MyViewController.

but MainViewController can't change UIButton title in MyViewController.

also, in MyViewController only change UIButton title in viewDidLoad method.

What's wrong?

MyViewController

@interface MyViewcontroller : UIViewController {
    IBOutlet UIButton *imageButton;
}

@property (nonatomic, retain) UIButton *imageButton;

@implementation MyViewcontroller : UIViewController {
@synthesize imageButton;
    - (void)viewDidLoad { // can change button title
        [imageButton setTitle:@"buttonTitle" forState:UIControlStateNormal]
    }

    - (void)setButtonTitle { // can't change button title
        [imageButton setTitle:@"buttonTitle" forState:UIControlStateNormal];
    }
}

MainViewController

@implementation MainViewController : UIViewController {
@synthesize scrollView;
    - (void)viewDidLoad { // can't change button title
        MyViewcontroller *myView = [[MyViewcontroller alloc] initWithNibName:@"MyViewcontroller" bundle:nil];
        [myView.imageButton setTitle:@"ddd" forState:UIControlStateNormal];
        [scrollView addSubview:myView.view];
        [myView release], myView = nil;
    }
}
like image 679
seapy Avatar asked Oct 10 '10 04:10

seapy


1 Answers

It happens because the outlets don't get wired until after the view is loaded, and the view doesn't get loaded until after it gets called for the first time (it's lazy loading). You can fix this very easily by just ensuring that you always load the view first. However, you might want to reconsider your design and make the button title dependent on some other item that's not part of the view hierarchy.

For example, if you re-order your calls, it will work:

MyViewcontroller *myView = [[MyViewcontroller alloc] initWithNibName:@"MyViewcontroller" bundle:nil];
[scrollView addSubview:myView.view]; // view is loaded
[myView.imageButton setTitle:@"ddd" forState:UIControlStateNormal]; // imageButton is now wired
like image 91
Jason Coco Avatar answered Oct 22 '22 13:10

Jason Coco