-1

I have a problem to setting the constraints of a custom uiview which is loaded from nib and added as subview to a containerview. I'm trying to add the constraints in the willMove(toSuperView) method but it's not working as expected. Where is the most appropriate place to set constraints of a custom UIView ?

Heres the code;

extension ErrorView {

    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        guard let newSuperview = newSuperview else { return }
        translatesAutoresizingMaskIntoConstraints = false
        newSuperview.setConstraintHeight(to: self)
        SetConstraintWidth(to: newSuperview)
    }
}

the setConstraintWidth and setConstraintHeight method names are placeholders. You can think as they are methods to setting the constraints.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
L'lynn
  • 167
  • 1
  • 13

2 Answers2

0

From what I knwo overriding layoutsubviews() will do the work

override func layoutSubviews() {
    super.layoutSubviews()
    //funky stuff here
}

here's a great answer for a similar issue : Proper practice for subclassing UIView?

0

From Apple's docs (https://developer.apple.com/documentation/uikit/uiview/1622629-willmove):

Tells the view that its superview is about to change to the specified superview.

So, that is taking place before the view is added to the new view.

Overriding didAddSubview() is probably a better place to add your constraints.

DonMag
  • 69,424
  • 5
  • 50
  • 86