Simone D'Amico
Simone D'Amico

Reputation: 2345

Can't set UILabel#preferredMaxLayoutWidth in layoutSubviews after constraints are in place

What are your best practising when you subclass UIView? I'm trying to do a view for a viewcontroller entirely in code, using the new ios 6 autolayout. So I've subclassed UIView and setup the basic constraints in #initWithFrame (should I do this in #updateConstraints?). The problem is that I have an UILabel with dynamic text and variable width so I have to setup #preferredMaxLayoutWidth after the constraints have determined a frame, so I think #layoutSubviews is the best place to do that, but doing that results in a NSInternalInconsistencyException: Auto Layout still required after executing -layoutSubviews. MyView's implementation of -layoutSubviews needs to call super. (RuntimeError) Before you asks I'm sure I have called super in every method I overridden. Any idea?

Upvotes: 2

Views: 1269

Answers (2)

headache
headache

Reputation: 138

This seemed to work for me, I can't explain why, but it did.

-(void)layoutSubviews
{
[super layoutSubviews];

layout code here, including updated constraints 

[super layoutSubviews];
}

Upvotes: 1

Nirav Bhatt
Nirav Bhatt

Reputation: 6969

Perhaps what you need here is to not have your view call [super layoutSubviews], but UIView, the ancestor, call its [super layoutSubviews].

This can be achieved not by subclassing, but implementing a category of UIView, which would have layoutSubViews function implemented, calling super. If I could have your code I could have tried. Someone has tried it successfully here.

Again, this does not guarantee that this will be fixed. There seems to be many bug reports concerning this in Apple forums. Unfortunately, we can't browse others' bugs in Apple portal, we can just file our own.

As a workaround, I would also suggest if any of your constraints conflict with your preferredMaxLayoutWidth argument: try increasing or decreasing it. As per the overriding order of its own, it can change things, and who (other than Apple) knows - it maybe fixed. Fingers crossed!

Upvotes: 1

Related Questions