ios - 为加载的 .xib 分配属性

标签 ios cocoa-touch interface-builder xib

我正在尝试更改正在加载的 .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";

并且通过一个自定义的setter方法,

- (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从 Nib 加载的对象;它已经被初始化了。

我建议您将该语句分成几个步骤,并确保每个步骤都能提供您期望的结果 - 当然,并放弃 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/

相关文章:

ios - 为什么我的应用程序在我向 TableView 中添加插入行时崩溃?

ios - Xcode 的界面生成器中是否有针对较小 iPhone 的尺寸变体?

ios - 类扩展 vs 主接口(interface) vs 类别

ios - 如何删除 View 和更新约束?

ios - <__NSCFDictionary : 0x1557f400> was mutated while being enumerated.'

objective-c -/var/log/syslog 在 iOS 中等效?

ios - Facebook 图表 API : Event timezone, 时间

iphone - 实现 UITableView 树结构

ios - 如何在 IB 中创建 PKPaymentButton?

ios - 我怎样才能让 UIButton 粘在 UIView 的底部