Swift Update Constraint

后端 未结 3 1061
逝去的感伤
逝去的感伤 2021-01-04 20:01

I added the constraint to the buttons created in my UIView

func CreateButtonWithIndex(index:Int) {

    newButton.setTranslatesAutoresizingMaskI         


        
3条回答
  •  长发绾君心
    2021-01-04 20:50

    Looks like you are just adding more and more constraint. You can't do that because they obviously conflict with each other. You are basically saying "put the view at position x = 1, x = 2, x = 3, x = 4 and x = 5".

    You have to remove the old constraints. You have two options to do that.

    1. Save the constraints in an array, and remove these constraints from the view before adding new ones.

    2. Or you keep a reference to the constraints that change and adjust their properties.

    Since your constraints just differ in the constant value you should go for option 2.

    Make newButtonConstraintX and newButtonConstraintY a variable of the viewController.

    e.g.

    class ViewController: UIViewController {
        var newButtonConstraintX: NSLayoutConstraint!
        var newButtonConstraintY: NSLayoutConstraint!
    
    
        func CreateButtonWithIndex(index:Int) {
    
            newButtonConstraintX = NSLayoutConstraint(item: newButton, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: CGFloat(riga))
    
            newButtonConstraintY = NSLayoutConstraint(item: newButton, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: CGFloat(colonna))
    
            /* ... */
        }
    
        func pan(rec:UIPanGestureRecognizer) {  
            /* ... */
            newButtonConstraintX.constant = line
            newButtonConstraintY.constant = column
            button.layoutIfNeeded()
        }
    

提交回复
热议问题