简体   繁体   English

使用代码而非情节提要添加的View自动布局(VFL)

[英]Autolayout (VFL) for View that is added with code not storyboard

If I add views from storyboard I can handle their autolayout contraints via code, but if I try this on a view that is added via code, can't handle it. 如果从情节提要中添加视图,则可以通过代码处理其自动布局约束,但是如果在通过代码添加的视图中尝试使用此布局,则无法处理。

I'm calling the code below in my viewDidLoad() but doesn't works, what is the missing part? 我在viewDidLoad()中调用以下代码,但不起作用,缺少的部分是什么?

    var testView = UIView()
    testView.backgroundColor = UIColor.greenColor()
    self.view.addSubview(testView)

    let views : [String : AnyObject] = ["testView": testView]
    var allConstraints = [NSLayoutConstraint]()

    let verticalConstraint = NSLayoutConstraint.constraintsWithVisualFormat(
        "V:|-[testView(100)]",
        options: [],
        metrics: nil,
        views: views)
    allConstraints += verticalConstraint

    let horizontalConstraint = NSLayoutConstraint.constraintsWithVisualFormat(
        "H:|-[testView(200)]",
        options: [],
        metrics: nil,
        views: views)
    allConstraints += horizontalConstraint

    NSLayoutConstraint.activateConstraints(allConstraints)

ps: also tried these lines but didn't help ps:也尝试过这些方法,但没有帮助

    self.view.addConstraints(verticalConstraint)
    self.view.addConstraints(horizontalConstraint)

You need to turn off translation of autoresizing masks to constraints. 您需要关闭自动调整大小掩码到约束的转换。 By default its set to true and if you tend to forget this, it will add constraints which you did not intend to. 默认情况下,将其设置为true ,如果您倾向于忘记此设置,它将添加您不希望的约束。

You can set this to false by 您可以将其设置为false

var myView = UIView()
myView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(myView)

translatesAutoresizingMaskIntoConstraints 将AutoresizingMask转换为约束

If this property's value is YES, the system creates a set of constraints that duplicate the behavior specified by the view's autoresizing mask. 如果此属性的值为YES,则系统将创建一组约束,这些约束将复制由视图的自动调整大小掩码指定的行为。 By default, the property is set to YES for any view you programmatically create. 默认情况下,以编程方式创建的任何视图的属性均设置为YES。 If you add views in Interface Builder, the system automatically sets this property to NO. 如果在Interface Builder中添加视图,则系统会自动将此属性设置为NO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM