【问题标题】:How to Change UIButton title?如何更改 UIButton 标题?
【发布时间】:2010-10-10 04:34:13
【问题描述】:

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

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

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

怎么了?

我的视图控制器

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

主视图控制器

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

【问题讨论】:

    标签: iphone ios uibutton


    【解决方案1】:

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

    例如,如果您重新排序呼叫,它将起作用:

    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
    

    【讨论】:

    • 我在按钮上设置文本时遇到了麻烦,因为我使用的是setImage 而不是setBackgroundImage。如果您使用setImage,它将覆盖您的文本。
    猜你喜欢
    • 2012-02-16
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多