How to add constraints programmatically using Swift

前端 未结 17 1168
逝去的感伤
逝去的感伤 2020-11-21 23:07

I\'m trying to figure this out since last week without going any step further. Ok, so I need to apply some constraints programmatically

17条回答
  •  情书的邮戳
    2020-11-21 23:25

    The problem, as the error message suggests, is that you have constraints of type NSAutoresizingMaskLayoutConstraints that conflict with your explicit constraints, because new_view.translatesAutoresizingMaskIntoConstraints is set to true.

    This is the default setting for views you create in code. You can turn it off like this:

    var new_view:UIView! = UIView(frame: CGRectMake(0, 0, 100, 100))
    new_view.translatesAutoresizingMaskIntoConstraints = false
    

    Also, your width and height constraints are weird. If you want the view to have a constant width, this is the proper way:

    new_view.addConstraint(NSLayoutConstraint(
        item:new_view, attribute:NSLayoutAttribute.Width,
        relatedBy:NSLayoutRelation.Equal,
        toItem:nil, attribute:NSLayoutAttribute.NotAnAttribute,
        multiplier:0, constant:100))
    

    (Replace 100 by the width you want it to have.)

    If your deployment target is iOS 9.0 or later, you can use this shorter code:

    new_view.widthAnchor.constraintEqualToConstant(100).active = true
    

    Anyway, for a layout like this (fixed size and centered in parent view), it would be simpler to use the autoresizing mask and let the system translate the mask into constraints:

    var new_view:UIView! = UIView(frame: CGRectMake(0, 0, 100, 100))
    new_view.backgroundColor = UIColor.redColor();
    view.addSubview(new_view);
    
    // This is the default setting but be explicit anyway...
    new_view.translatesAutoresizingMaskIntoConstraints = true
    
    new_view.autoresizingMask = [ .FlexibleTopMargin, .FlexibleBottomMargin,
        .FlexibleLeftMargin, .FlexibleRightMargin ]
    
    new_view.center = CGPointMake(view.bounds.midX, view.bounds.midY)
    

    Note that using autoresizing is perfectly legitimate even when you're also using autolayout. (UIKit still uses autoresizing in lots of places internally.) The problem is that it's difficult to apply additional constraints to a view that is using autoresizing.

提交回复
热议问题