How to increase height of particular subview of st

2019-08-17 01:32发布

问题:

I have added some arrangedSubViews to vertical UIStackView. and I want to increase height of one arranged subview inside on tap of some button.

Tried adding layoutIfNeeded on subview and main view. Its Not working.

I am increasing height of subview as below :

addConstraints([self.heightAnchor.constraint(equalToConstant: 100)])
layoutIfNeeded()
sizeToFit()
layoutSubviews()

回答1:

I think the problem is that you are trying to add a new constraint to the view but you didn't deactivate the existing constraint for heightAnchor.

You could either set the isActive property of the existing height constraint to false before adding a new constraint or simply set the constant of the existing height constraint to a new value.

You can give the constraint an identifier which you can use later to get that specific constraint and change its property.

If I were you, I would add the following two extensions to my code:

extension UIView {
    func getConstraint(withIndentifier indentifier: String) -> NSLayoutConstraint? {
        return self.constraints.filter { $0.identifier == indentifier }.first
    }
}

extension NSLayoutConstraint {
    func activate(withIdentifier identifier: String) {
        self.identifier = identifier
        self.isActive = true
    }
}

Example Usage:

// When you create the constraint:
subview.heightAnchor.constraint(equalToConstant: 100).activate(withIdentifier: "THE")

// When you want to change the constant:
if let filteredConstraint = subview.getConstraint(withIndentifier: "THE") {
    filteredConstraint.constant = 500
}

If you want animation, just add the following code right after you changed the constraints:

UIView.animate(withDuration: 0.5) {
    self.view.layoutIfNeeded()
}

I believe this will work, otherwise please let me know.


Update

When you set the constraint like this:

self.myStackView.topAnchor.constraint(equalTo: someView.bottomAnchor , constant: 20).activate(withIdentifier: "topAnchor") 

The constraint actually belongs to neither myStackView nor someView, but their superview. Although matt's answer is correct, personally I prefer Kh_khan's answer in the comment:

self.myStackView.superView?.getConstraint(withIndentifier: "topAnchor")

Let me know whether it works.