簡體   English   中英

如何更改UIButton標題?

[英]How to Change UIButton title?

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

之所以發生這種情況,是因為插座只有在加載視圖之后才進行接線,並且只有在第一次調用視圖之后才加載視圖(這是延遲加載)。 您只需確保始終先加載視圖即可非常輕松地解決此問題。 但是,您可能需要重新考慮設計,並使按鈕標題依賴於其他不屬於視圖層次結構的項目。

例如,如果您對電話重新排序,它將起作用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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