在我的應用程序中,我想添加一個或多個UITextFields並點擊按鈕。我可以在自定義UIView(在Storyboard中預定義)中創建UITextFields,但是我無法正確地將約束添加到UIView的按鈕(按鈕位於UIView下)的文本字段和約束中。所以每按一下按鈕,我想調整UIView的大小,並在添加文本字段後按下按鈕。現在我使用此代碼,它增加了文本字段成功,但約束不工作:添加帶約束的UITextField programmaticaly
@IBAction func addCustomTextField(sender: AnyObject) {
let x : CGFloat = 20
var y : CGFloat = 10
let width : CGFloat = 300
let height : CGFloat = 40
var lastButtonY : Int? = NSUserDefaults.standardUserDefaults().integerForKey("lastButtonY")
if lastButtonY > 0 {
y = CGFloat.init(lastButtonY! + 8)
NSUserDefaults.standardUserDefaults().setObject(y + height, forKey: "lastButtonY")
} else {
NSUserDefaults.standardUserDefaults().setObject(10 + height, forKey: "lastButtonY")
}
sampleTextField = UITextField(frame: CGRectMake(x, y, width, height))
sampleTextField.placeholder = "Enter text here"
sampleTextField.font = UIFont.systemFontOfSize(15)
sampleTextField.borderStyle = UITextBorderStyle.RoundedRect
sampleTextField.autocorrectionType = UITextAutocorrectionType.No
sampleTextField.keyboardType = UIKeyboardType.Default
sampleTextField.returnKeyType = UIReturnKeyType.Done
sampleTextField.clearButtonMode = UITextFieldViewMode.WhileEditing;
sampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
self.customView.addSubview(sampleTextField)
let bottomConstraintForTextField = NSLayoutConstraint(item: sampleTextField, attribute: .Bottom, relatedBy: .Equal, toItem: customView, attribute: .Bottom, multiplier: 1, constant: 10)
let bottomConstraintForCustomView = NSLayoutConstraint(item: customView, attribute: .Bottom, relatedBy: .Equal, toItem: addButton, attribute: .Bottom, multiplier: 1, constant: 10)
NSLayoutConstraint.activateConstraints([bottomConstraintForTextField, bottomConstraintForCustomView])
}
爲什麼不使用TableView? – UlyssesR