我想以编程方式将UITextField添加到我的View中。 左边和右边的距离应为20。 距离顶部的距离应为100.
如果我在设计器中添加约束它可以工作: - >在模拟器中看起来像这样:
我的代码现在:
let EmailTextfield = UITextField()
override func loadView() {
super.loadView()
EmailTextfield.translatesAutoresizingMaskIntoConstraints = false
EmailTextfield.layer.borderWidth = 2
EmailTextfield.layer.borderColor = UIColor.blackColor().CGColor
EmailTextfield.addConstraint(
NSLayoutConstraint(
item: EmailTextfield,
attribute: NSLayoutAttribute.Height,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1.0,
constant: 40
))
//left
self.view.addConstraint(
NSLayoutConstraint(
item: EmailTextfield,
attribute: NSLayoutAttribute.Leading,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.Leading,
multiplier: 1.0,
constant: 20
))
//right
self.view.addConstraint(
NSLayoutConstraint(
item: EmailTextfield,
attribute: NSLayoutAttribute.Trailing,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.Trailing,
multiplier: 1.0,
constant: 20
))
//top
self.view.addConstraint(
NSLayoutConstraint(
item: EmailTextfield,
attribute: NSLayoutAttribute.Top,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.Top,
multiplier: 1.0,
constant: 100
))
)
我的错误是什么?
答案 0 :(得分:1)
尾随常量必须是负值-20而不是20。
答案 1 :(得分:0)
您可以将RIGHT约束常数从20更改为-20。或者你可以切换RIGHT约束项(item:self.view,toItem:EmailTextfield)并保持常量为20。