How to add constraints programmatically using Swift

前端 未结 17 1181
逝去的感伤
逝去的感伤 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:34

    You are adding all defined constraints to self.view which is wrong, as width and height constraint should be added to your newView.

    Also, as I understand you want to set constant width and height 100:100. In this case you should change your code to:

    var constW = NSLayoutConstraint(item: newView, 
        attribute: .Width, 
        relatedBy: .Equal, 
        toItem: nil, 
        attribute: .NotAnAttribute, 
        multiplier: 1, 
        constant: 100)
    newView.addConstraint(constW)
    
    var constH = NSLayoutConstraint(item: newView, 
        attribute: .Height, 
        relatedBy: .Equal, 
        toItem: nil, 
        attribute: .NotAnAttribute, 
        multiplier: 1, 
        constant: 100)
    newView.addConstraint(constH)
    

提交回复
热议问题