Reputation: 15
I am trying to hide and unhide a view. Its size should be 0 when it is hidden and about 200 when it is unhidden. I have two view controllers. When the first controller shows the view is hidden for the first time and its size is set to 0 and then it navigates to other controller and takes some values from the textfeilds and display them on a tableview in previous controller.
Now, I am able to hide the view for the first time with height 0 but when I take up the values the view is still hidden.
This is the code I have tried so far:
mainView.isHidden == true
mainView.heightAnchor.constraint(equalToConstant: CGFloat(0)).isActive = true
// when I get the values but this code doesn't work
mainView.isHidden == false
mainView.heightAnchor.constraint(equalToConstant: CGFloat(100)).isActive = true
Any help would be appreciated.
Upvotes: 0
Views: 2319
Reputation: 8347
You keep both created constraints in your view controller and activate however you need accordingly, using isActive
property of NSLayoutConstraint
:
var hiddenHeightConstraint: NSLayoutConstraint?
var showingHeightConstraint: NSLayoutConstraint?
var isMainViewHidden: Bool = false {
didSet {
mainView.isHidden == isMainViewHidden
hiddenHeightConstraint?.isActive = isMainViewHidden
showingHeightConstraint?.isActive = !isMainViewHidden
// Don't forget to call layoutIfNeeded() when you messing with the constraints
view.layoutIfNeeded()
}
}
override func viewDidLoad() {
super.viewDidLoad()
hiddenHeightConstraint = mainView.heightAnchor.constraint(equalToConstant: CGFloat(0))
showingHeightConstraint = mainView.heightAnchor.constraint(equalToConstant: CGFloat(100))
isMainViewHidden = false
}
Upvotes: 0
Reputation: 52
class viewController: UIViewController {
var height: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
height = mainView.heightAnch.constraint(equalToConstant: 0)
height.isActive = true
//handle change height
if mainView.isHidden == true {
height.constant = 0
}
else {
height.constant = 200
}
}
}
Upvotes: 2
Reputation: 432
You have two options. The first method set identifier to height constraint
set identifier:
then find and change with below code:
// first option
// find own constraint with indentifier
if let heightConstraint = self.myView.constraints.first(where: { item -> Bool in
return item.identifier == "heightIdentifier"
}) {
// set any constant to constraint
heightConstraint.constant = 200.0 // for hidden
heightConstraint.constant = 0.0 // for hide
// any work
}
second option: set IBOutlet to target constraint:
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
then change direct and simple:
// second option
// change constant direct
self.heightConstraint.constant = 200.0 // for hidden
self.heightConstraint.constant = 0.0 // for hide
// any work
Upvotes: 0