2015-12-15 58 views

回答

6

我喜欢在视图中设置自己的AutoLayout代码,当它更有意义。我还发现,将customView中的所有约束设置为init的一部分会更容易。

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])) 
    } 
} 
19

是否可以自定义的UIView中添加NSLayoutConstraints?

是的,可以在自定义视图中添加约束条件,组织在这里非常重要,尤其是如果您要为自定义视图的某些部分设置动画效果时。

从苹果公司的UIView Reference document

约束阅读子类部分:

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() { 
     super.updateConstraints() 

     if didSetupConstraints == false { 
      addConstraintsForMyLabel() 
     } 
    } 

    private func addConstraintsForMyLabel() { 

     // Add your constraints here 
    } 

} 
+0

@Tulleb我相信你忘了,如果限制在'updateConstraints)设置('设置'didSetupConstraints'到TRUE;。 –

+0

请问@fragilecat? – Tulleb

+0

@fragilecat如果在'updateConstraints()'中设置了约束,我相信你忘了将'didSetupConstraints'设置为'true'。 –

相关问题