问题
I have a subclass of UIButton on a view. Works great in iOS 6, 5, etc. But in iOS 7, I'm noticing delays when I try to change the title (using setTitle:forState:). I've tracked down the issue to the fact that the foundation is constantly calling layoutSubviews on my control, and this causing the CPU usage to hover around 100% for the lifetime of the app.
In my subclass, I overrode layoutSubviews and added a breakpoint to diagnose the problem. The backtrace only shows the method called from the [UIView layoutSublayersOfLayer] method in the foundation.
Note that if I comment out this line:
[super layoutSubviews];
the CPU problem goes away, but, of course, other problems arise.
Has anyone seen this? Why is iOS 7 calling layoutSubviews constantly?
回答1:
Found the problem. In my setEnabled: method (part of the reason for the subclass in the first place), I had the following line:
self.titleLabel.alpha = enabled ? 1.0 : 0.8;
And apparently in iOS 7, this causes UIButton to begin a title-change animation that it never finishes. The result is an infinite loop in which layoutSubviews is repeatedly called.
The fix was to include this line when the titleColor is changed:
[self setTitleColor:[[self titleColorForState:UIControlStateNormal] colorWithAlphaComponent:0.8] forState:UIControlStateDisabled];
And the infinite loop is averted!
来源:https://stackoverflow.com/questions/18991001/in-ios-7-layoutsubviews-method-is-called-constantly-on-uibutton-subclass