views:

47

answers:

1

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;
    }
}
+2  A: 

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
Jason Coco
thank you. i will learn lazy loading
seapy
I missed that bit — looks like I have plenty to learn +1
BoltClock