autolayout constraints are not updated in swift

If you have updated your views and the Autolayout constraints are not updating, you can try the following solutions:

  1. Call layoutIfNeeded() on the view. This forces the layout engine to update the constraints and relayout the view hierarchy.
main.swift
view.setNeedsLayout()
view.layoutIfNeeded()
44 chars
3 lines
  1. If you are updating constraints after the view has loaded, make sure you call layoutIfNeeded() on the view controller's view first. This ensures that the view hierarchy is initialized before the constraints are updated.
main.swift
self.view.layoutIfNeeded()
// Update constraints here
54 chars
3 lines
  1. Make sure the constraints are set up correctly. Check that the constraints are not conflicting or ambiguous. Use the Xcode debugger to see the layout errors.

  2. If you are using Autolayout in a custom view, make sure to override the intrinsicContentSize method to return the correct size.

main.swift
override var intrinsicContentSize: CGSize {
    return CGSize(width: 200, height: 100)
}
89 chars
4 lines
  1. If you are still having trouble, try removing the constraints, updating the views, and then adding the constraints back.
main.swift
NSLayoutConstraint.deactivate(constraints)
// Update views here
NSLayoutConstraint.activate(constraints)
105 chars
4 lines

gistlibby LogSnag