我正在尝试更改加载的.xib中按钮的标题:

CustomToolBar *toolBar = (CustomToolBar *)[[[[NSBundle mainBundle]
                                          loadNibNamed:@"CoolBar"
                                          owner:self options:nil] objectAtIndex:0]
                                          initWithFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 70)];


我试图直接使用更改它

toolBar.button.titleLabel.text = @"VALUE";


通过自定义设置方法

- (void)updateButtonText:(NSString *)buttonText {
    _button.titleLabel.text = buttonText;
}


但是,它始终默认为.xib文件中给定的值。

最佳答案

CustomToolBar *toolBar =
    (CustomToolBar *)[[[[NSBundle mainBundle]
        loadNibNamed:@"CoolBar"
        owner:self options:nil] objectAtIndex:0]
    initWithFrame:CGRectMake(
        0, self.view.frame.size.height, self.view.frame.size.width, 70)];


您的代码没有任何意义。您不能/不能init从笔尖加载的对象;它已经被初始化。

我建议您将语句分成几个步骤,并确保每个步骤都能为您带来预期的结果-当然不要使用init了。

NSArray* arr = [NSBundle mainBundle]
        loadNibNamed:@"CoolBar"
        owner:nil options:nil]; // did it load?
id obj = [arr objectAtIndex: 0]; // did you get the CustomToolbar?
CustomToolBar *toolBar =
    (CustomToolBar *) obj; // still ok?
toolbar.frame = CGRectMake(
    0, self.view.frame.size.height, self.view.frame.size.width, 70);


等等。

然后,您可以开始考虑要使用toolBar做什么。目前尚未将其放入您的界面中,因此您无法知道您的更改是否正在影响它。一旦完成,您就可以开始询问自己其余的代码。例如,尝试直接设置UIButton的titleLabel.text是疯狂的(并且是错误的)。这不是按钮的工作方式。拥有toolBar后,您可以说

[toolBar.button setTitle:@"VALUE" forState: UIControlStateNormal];

关于ios - 将属性分配给已加载的.xib,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29907398/

10-14 20:17
查看更多