How to update the constant height constraint of a UIView programmatically?
Select the height constraint from the Interface builder and take an outlet of it. So, when you want to change the height of the view you can use the below code.
yourHeightConstraintOutlet.constant = someValue
yourView.layoutIfNeeded()
Method updateConstraints()
is an instance method of UIView
. It is helpful when you are setting the constraints programmatically. It updates constraints for the view. For more detail click here.
Update the constant property of a constraint programmatically in Swift?
In order to declare an animation, you cannot re-define the constraint and call updateConstraints
. You are supposed to change the constant
of your constraint and follow the format below:
self.view.layoutIfNeeded()
UIView.animate(withDuration: 1) {
self.sampleConstraint.constant = 20
self.view.layoutIfNeeded()
}
Modify constraint programmatically Swift
So this is the way I achieved this :
Create a constraint programmatically (height in my case) :
// Drawing height property
var drawingHeightConstraint: NSLayoutConstraint?Deactivate old constraint and set the new one if needed
Note: heightContraints is an array of NSLayoutConstraint which contains my outlets
for (index, (drawing, ratio)) in drawingElements.enumerate() {
drawingViews[index].image = UIImage(named: drawing)
// update height constraint if ratio is different than defaut ratio of 1/2
if ratio != 0.5 {
heightConstraints[index].active = false
drawingHeightConstraint = NSLayoutConstraint(item: drawingViews[index], attribute: .Height, relatedBy: .Equal, toItem: drawingView, attribute: .Height, multiplier: CGFloat(ratio), constant: 0)
drawingHeightConstraint!.active = true
}
}
- Call layoutIfNeeded() right after (note: not sure when to call it)
Update height constraint programmatically
Instead of adding a new constraint, you need to modify the constant on your existing constraint.
Use an IBOutlet to connect to your constraint in Interface Builder:
@property (nonatomic, weak) NSLayoutConstraint *heightConstraint;
Then, when you need to set it programmatically, simply set the constant property on the constraint:
heightConstraint.constant = 100;
OR
If you can't access the nib in Interface Builder, find the constraint in code:
NSLayoutConstraint *heightConstraint;
for (NSLayoutConstraint *constraint in myView.constraints) {
if (constraint.firstAttribute == NSLayoutAttributeHeight) {
heightConstraint = constraint;
break;
}
}
heightConstraint.constant = 100;
And in Swift:
if let constraint = (myView.constraints.filter{$0.firstAttribute == .width}.first) {
constraint.constant = 100.0
}
Updating constraints in swift 5
first declare the variable, after set start constraints variable to true and after call a function that active and dis active constraints, try with my example:
under controller class declare a button and a view do you want to move:
let dummyView = UIView()
let button = UIButton(type: .system)
after declare variable to move your view with constraint:
var up: NSLayoutConstraint?
var down: NSLayoutConstraint?
in ViewDiLoad set the view, the button and the constraints like this:
dummyView.backgroundColor = .yellow
dummyView.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("viewDiwn", for: .normal)
button.backgroundColor = .red
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = .systemFont(ofSize: 16)
button.addTarget(self, action: #selector(handletapButton), for: .touchUpInside)// button action that call handletapButton func
button.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(dummyView)
up = dummyView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor)
up?.isActive = true // start constraint active
down = dummyView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 100) // constraint to activate for move the view
dummyView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
dummyView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
dummyView.heightAnchor.constraint(equalToConstant: 50).isActive = true
view.addSubview(button)
button.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
button.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
button.heightAnchor.constraint(equalToConstant: 50).isActive = true
button.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
now write the function to move the view by constraint animation:
@objc func handletapButton() {
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseOut, animations: {
self.up?.isActive = false
self.down?.isActive = true
self.view.layoutIfNeeded()
}, completion: nil)
}
this is the result
changing constraints at runtime in swift
just make the outlet of height of both UIView and use constant property to change the height constraints like...
if conditionfails{
heightconstOfView1.constant = 0
}
else{
heightconstOfView2.constant = 0
}
can't change constraint.constant programmatically in viewDidLoad:
See that wR hR
option under Constant
? That was the problem. Looks like constraints that use size classes cant be set in viewDidLoad.
Related Topics
What Is Sandbox in iOS? How to Transfer Data Between One App to Another App
How to Force a Hkquery to Load the Most Recent Steps Counts
Xcode - Bundle Format Unrecognized, Invalid, or Unsuitable
Swiftui Datepicker Binding Optional Date, Valid Nil
Unexpected Non-Void Return Value in Void Function Swift3
Core Data in Swift: Only Saving Last Object in a for Loop
iOS 5 JSON Parsing Results in Cocoa Error 3840
How to Lookup a String Constant at Runtime in Objective-C
Moving the Cursor to the Beginning of Uitextfield
Nsxmlparser: Unexpected Result with Non-Ascii Characters
Recording to Aac from Remoteio: Data Is Getting Written But File Unplayable
How to Install Older iOS Simulators in Xcode 4.2.1 (Sdk5.0)
How to Get a Cgpoint from a Tapped Location
Using Ldap for Authentication in iOS