Search code examples
iosswift3nslayoutconstraintnslayoutanchor

changing layout anchors of view on an action


I have one upperLabel, one view and button.

In ViewDidLoad() method I have given some layout constraints to a view. On tap of the button I need to update those constraints(i.e the view should move downwards). How can I do that.

Here is my code for that. But it is not working.

let keyView = UIView()

override func viewDidLoad() {

    keyView.frame = CGRect(x: 0, y: 0, width: 100, height: 30)
    keyView.backgroundColor = UIColor.cyan
    keyView.translatesAutoresizingMaskIntoConstraints = false
    containerView.addSubview(keyView)
    keyView.topAnchor.constraint(equalTo: upperLabel.bottomAnchor , constant: 10).isActive = true
    keyView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 20).isActive = true
    keyView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -20).isActive = true
    keyView.bottomAnchor.constraint(equalTo: keyView.topAnchor, constant: keyView.frame.size.height).isActive = true
}

Code in that action is as follows.

  func buttonAction(sender: UIButton!) {

    keyView.translatesAutoresizingMaskIntoConstraints = false
    keyView.topAnchor.constraint(equalTo: upperLabel.bottomAnchor, constant: CGFloat(i*50))
    keyView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 20)
    keyView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -20)
    keyView.bottomAnchor.constraint(equalTo: keyView.topAnchor, constant: keyView.frame.size.height)
    i + =1
}

As per the above code the keyView should move downwards on clicking of the button. But it is not moving down.

Please help me out. Thanks in advance.


Solution

  • Take a global variable which is of type NSLayoutConstraint which is as follows..

    var keyViewTopConstraint: NSLayoutConstraint?

    Now in viewDidLoad while giving initial constraints. Give as follows

        keyViewTopConstraint = keyView.topAnchor.constraint(equalTo: upperLabel.bottomAnchor , constant: 10)
        keyViewTopConstraint?.isActive = true
    

    Now in that action. remove initial constraint and create another constraint and make it as active. For that do as follows

       keyViewTopConstraint?.isActive = false
       keyViewTopConstraint = keyView.topAnchor.constraint(equalTo: upperLabel.bottomAnchor, constant: CGFloat(i*50))
       keyViewTopConstraint?.isActive = true