如何更改UIButton标题?

时间:2010-10-10 04:34:13

标签: iphone ios uibutton

MyViewController有一个UIButton,另一个MainViewController使用MyViewController。

但是MainViewController无法在MyViewController中更改UIButton标题。

另外,在MyViewController中只更改viewDidLoad方法中的UIButton标题。

怎么了?

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;
    }
}

1 个答案:

答案 0 :(得分:39)

之所以发生这种情况,是因为在加载视图之后才会连接出口,并且在第一次调用它之后才会加载视图(它是延迟加载)。您可以通过确保始终首先加载视图来轻松解决此问题。但是,您可能需要重新考虑您的设计,并使按钮标题依赖于不属于视图层次结构的其他项目。

例如,如果您重新订购呼叫,它将起作用:

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