在iOS 7中,在UIButton子类上不断调用layoutSubviews方法 [英] In iOS 7, layoutSubviews method is called constantly on UIButton subclass
问题描述
我在视图上有一个UIButton的子类。适用于iOS 6,5等。但在iOS 7中,当我尝试更改标题时,我注意到延迟(使用setTitle:forState :)。我已经将问题追溯到这样一个事实:基金会不断在我的控件上调用layoutSubviews,这导致CPU使用率在应用程序的生命周期内徘徊在100%左右。
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.
在我的子类中,我覆盖了layoutSubviews并添加了一个断点来诊断问题。回溯仅显示从基础中的[UIView layoutSublayersOfLayer]方法调用的方法。
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];
CPU问题消失了,但当然,其他问题出现。
the CPU problem goes away, but, of course, other problems arise.
有没有人见过这个?为什么iOS 7会不断调用layoutSubviews?
Has anyone seen this? Why is iOS 7 calling layoutSubviews constantly?
推荐答案
发现问题。在我的setEnabled:方法(首先是子类的部分原因)中,我有以下几行:
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;
显然在iOS 7中,这会导致UIButton开始一个永远不会完成的标题更改动画。结果是一个无限循环,其中layoutSubviews被重复调用。
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.
当titleColor改变时,修复是包括这一行:
The fix was to include this line when the titleColor is changed:
[self setTitleColor:[[self titleColorForState:UIControlStateNormal] colorWithAlphaComponent:0.8] forState:UIControlStateDisabled];
避免无限循环!
这篇关于在iOS 7中,在UIButton子类上不断调用layoutSubviews方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!