Ber*_*rnd 27 uikit uiview ios autolayout swift
我经常看到自动布局约束被添加UIViewController到我看来,这似乎是布局逻辑的错误位置.
可以NSLayoutConstraint在自定义中添加s UIView吗?
在哪里UIView可以通过编程方式添加它们?
Pet*_*sby 34
是否可以在自定义UIView中添加NSLayoutConstraints?
是的,可以在自定义视图中添加约束,组织在这里非常重要,特别是如果您想要为自定义视图的某些部分设置动画.
阅读Apple的UIView参考文档中的子类化部分
约束:
requiresConstraintBasedLayout - 如果视图类需要约束才能正常工作,请实现此类方法.
updateConstraints - 如果您的视图需要在子视图之间创建自定义约束,请实现此方法.
alignmentRectForFrame:,frameForAlignmentRect: - 实现这些方法以覆盖视图与其他视图对齐的方式.
在UIView中哪里是以编程方式添加它们的正确位置?
这是自定义类的骨架轮廓.关键问题是您集中了约束,否则您添加的约束越多,类就会变得非常混乱.您还可以在updateConstraints()方法中引入其他设置,并通过设置配置值有条件地添加或删除约束,然后调用setNeedsUpdateConstraints().
您决定要设置动画的任何约束应该最简单的是实例变量.
希望这可以帮助 :)
class MyCustomView: UIView {
private var didSetupConstraints = false
private let myLabel = UILabel(frame: CGRectZero)
// MARK: Lifecycle
override init(frame: CGRect) {
super.init(frame: CGRectZero)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
// Mark: - Setup
private func setup() {
// 1. Setup the properties of the view it's self
self.translatesAutoresizingMaskIntoConstraints = false
backgroundColor = UIColor.orangeColor()
clipsToBounds = true
// 2. Setup your subviews
setupMyLabel()
// 3. Inform the contraints engine to update the constraints
self.setNeedsUpdateConstraints()
}
private func setupMyLabel() {
myLabel.translatesAutoresizingMaskIntoConstraints = false
}
override func updateConstraints() {
if didSetupConstraints == false {
addConstraintsForMyLabel()
}
super.updateConstraints() //Documentation note: Call [super updateConstraints] as the final step in your implementation.
}
private func addConstraintsForMyLabel() {
// Add your constraints here
}
}
Run Code Online (Sandbox Code Playgroud)
小智 8
我更喜欢在视图中设置我的AutoLayout代码.我还发现,在一个地方设置所有约束作为customView初始化的一部分更容易.
import UIKit
class customView:UIView
{
var customLabel:UILabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
self.setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI()
{
// Setup UI
self.customLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(customLabel)
// Setup Constraints
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[customLabel]|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["customLabel":self.customLabel]))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[customLabel]-10-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["customLabel":self.customLabel]))
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13823 次 |
| 最近记录: |