我是 AutoLayout 的新手,我想以 100% 的宽度显示我的 UITextField,并保持一致的 15px 左右边距,如下所示:
通常我会使用 CGRect 来执行此操作,将宽度设置为包含 View 的宽度减去 30 像素,然后将左侧偏移 15 像素:
searchTextField.frame = CGRectMake(15, 0, view.frame.width - 30, 50)
但是我想为这类事情学习 AutoLayout,因为现在这是一种方式。我应该指出,我正在以编程方式做所有事情——这里没有 Storyboard 。
如果有人能帮助我,我会很高兴!
更新
哇!感谢您的所有回复。我相信他们所有人都会实现我想要做的事情,但只能有一个:)
最佳答案
通常我使用这个处理约束的 cocoapod,但如果你需要纯苹果解决方案文档说明:
You have three choices when it comes to programmatically creating constraints: You can use layout anchors, you can use the NSLayoutConstraint class, or you can use the Visual Format Language.
在您的案例中使用 NSLayoutConstraints 的方法是:
NSLayoutConstraint(item: textField, attribute: .Leading, relatedBy: .Equal, toItem: parentView, attribute: .LeadingMargin, multiplier: 1.0, constant: 15.0).active = true
NSLayoutConstraint(item: textField, attribute: .Trailing, relatedBy: .Equal, toItem: parentView, attribute: .TrailingMargin, multiplier: 1.0, constant: -15.0).active = true
NSLayoutConstraint(item: textField, attribute: .Top, relatedBy: .Equal, toItem: parentView, attribute: .TopMargin, multiplier: 1.0, constant: 50.0).active = true
请记住,如果您在 View 中没有任何约束,它们将自动添加,您将不得不处理它们以及通过在运行时添加新约束而产生的冲突。为避免这种情况,您可以手动创建 textField 并将其添加到 View 或在 Interface Builder 中设置低优先级的约束。
关于ios - 以编程方式带有边距的 UITextField 自动布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37506014/