2016-07-31 35 views
0

我想將UITextField添加到UITableCell中並將它的寬度和高度都設置爲100%;Swift當使用Visual Format語言的UITextField的addConstraints時出現錯誤

我的SWIFT代碼:

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>>' 

回答

2

很奇怪,你是沒有指定一個視圖中調用addSubview。通常它的用法如下:

cell.contentView.addSubview(nameTextField) 

由於您未指定視圖,因此它必須使用self

VFL返回的約束涉及兩個視圖:您的nameTextField及其超級視圖。在VFL中,"|"代表超級視圖,因此它不必顯式包含在您傳入的view字典中。您需要將約束添加到層次結構中較高的視圖。在你的情況下,你需要將約束添加到nameTextField的超級視圖,即self。所以你可以這樣做:

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

從iOS 8開始,有一個更簡單的方法。約束條件知道需要添加哪些視圖,因此您只需將其active屬性設置爲true即可。 VFL可以返回多個約束,因此您需要使它們全部處於活動狀態。您可以使用NSLayoutConstraint的分類方法activateConstraints來激活多個約束:

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) 
相關問題