ios 如何更改 UIButton 标题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3899048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:52:08  来源:igfitidea点击:

How to Change UIButton title?

iphoneiosuibutton

提问by seapy

MyViewController has one UIButton and another MainViewController use MyViewController.

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

but MainViewController can't change UIButton title in MyViewController.

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

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

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

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

回答by Jason Coco

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