0

我想将 UITextField 添加到 UITableCell 中并将其宽度和高度设置为 100%;

我的快速代码:

nameTextField.translatesAutoresizingMaskIntoConstraints = false

addSubview( nameTextField )    

let views = [
    "name" : nameTextField
];

let widthLayoutConstraint = NSLayoutConstraint.constraintsWithVisualFormat( "H:|-[name]-|", options: [], metrics: nil, views: views )
nameTextField.addConstraints( widthLayoutConstraint )
let heightLayoutConstraint = NSLayoutConstraint.constraintsWithVisualFormat( "V:|-[name]-|", options: [], metrics: nil, views: views )
nameTextField.addConstraints( heightLayoutConstraint )

当表格显示时,我收到以下错误消息:

2016-07-31 19:16:43.027 NOIB[40193:1889520] *** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to install constraint on view.  Does the constraint reference something from outside the subtree of the view?  That's illegal. constraint:<NSLayoutConstraint:0x7ffbfa70f480 UITextField:0x7ffbfa41dff0.leading == NOIB.NameCell:0x7ffbfa41da10'NameCell'.leadingMargin> view:<UITextField: 0x7ffbfa41dff0; frame = (0 0; 0 0); text = ''; clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x7ffbfa41e5c0>>'
4

1 回答 1

2

奇怪的是您在addSubview没有指定视图的情况下调用。通常它像这样使用:

cell.contentView.addSubview(nameTextField)

由于您没有指定视图,因此它必须使用self.

VFL 返回的约束中涉及两个视图:您nameTextField的视图和它的父视图。在 VFL 中,"|"表示超级视图,因此它不必显式包含在view您传入的字典中。您需要将约束添加到层次结构中较高的视图。在您的情况下,您需要将约束添加到 的超级视图nameTextField,即self. 所以你可能会这样做:

self.addConstraints(widthLayoutConstraint)
self.addConstraints(heightLayoutConstraint)

从 iOS 8 开始,有一种更简单的方法。约束知道需要将它们添加到哪些视图,因此您只需将它们的active属性设置为true. VFL 可以返回多个约束,因此您需要将它们全部激活。您可以使用 的类方法activateConstraintsNSLayoutConstraint激活多个约束:

let widthLayoutConstraint = NSLayoutConstraint.constraintsWithVisualFormat( "H:|-[name]-|", options: [], metrics: nil, views: views )
NSLayoutConstraint.activateConstraints(widthLayoutConstraint)
let heightLayoutConstraint = NSLayoutConstraint.constraintsWithVisualFormat( "V:|-[name]-|", options: [], metrics: nil, views: views )
NSLayoutConstraint.activateConstraints(heightLayoutConstraint)
于 2016-07-31T11:50:22.013 回答