我刚刚目睹了一个非常奇怪的问题,我的 View 会忽略来自自定义 View 的所有委托(delegate)调用,因为我在加载时对项目调用了 alloc/init。我很好奇为什么。
@synthesize customTextField;
-(void)viewDidLoad {
// by calling this alloc/init, none of the changes here actually update to the view
// everything is ignored from here on in.
// if I comment out the alloc/init line, everything works fine
self.customTextField = [[UITextField alloc] init];
self.customTextField.text = @"Some text";
// setting font and size as well
}
虽然我仍然会收到对文本字段委托(delegate)方法的调用,但没有一个与我的特定文本字段相关联。我无法仅响应 customTextField
。
我确实意识到调用 alloc/init 会给我一个全新的 customTextField
实例...但是为什么那个新实例不链接到 IB 和我的 View ?
最佳答案
因为 IB 链接 != 绑定(bind)
。
当您在 IB 中链接一个变量时,它只是在第一次加载时简单地设置一次变量,仅此而已。它没有其他特殊代码来跟踪对其的任何更改,这是有充分理由的。
例如:
您正在设计一个 UITableViewCell
,如果您选择了一个单元格,则必须重新排列单元格内的所有内容。在这种情况下,您确定重新创建所有 subview 并将它们重新添加到 View 中会更容易,因此您执行以下操作:
-(void) layoutSubviews {
if (cellIsSelected)
{
// custom button is an IBOutlet property, which is by default a subview of self
self.customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[[self someSubView] addSubview:customButton];
}
else {
// where is customButton located now? is it a subview of self or `someSubView`?
self.customButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// [self addSubview:customButton];
}
}
因此,对于 IB 来说,说让我们设置一次,然后让程序员解决其余的问题
比 IB 尝试跟踪对对象所做的所有更改并报告它们要容易得多到用户界面。
关于ios - viewDidLoad 中的 alloc/init 导致 IB 忽略导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11604935/