【发布时间】:2016-02-18 21:00:54
【问题描述】:
在我的应用程序中,我想通过单击按钮添加一个或多个 UITextField。我可以在自定义 UIView(在 Storyboard 中预定义)中创建 UITextFields,但我无法正确地将约束添加到文本字段和 UIView 对 Button 的约束(按钮位于 UIView 下方)。因此,每次单击按钮时,我都想使用给定的约束调整 UIView 的大小,并在添加文本字段后向下移动按钮。现在我正在使用此代码,它成功添加了文本字段,但约束不起作用:
@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 ?
标签: ios xcode swift uitextfield