ios - 使用 Autolayout 设置 UIButton titleEdgeInsets 和 imageEdgeInsets 很慢

标签 ios objective-c uibutton uikit autolayout

我有一个 View ,其中包含几个不同大小的按钮。它们都有一个标题和一个图像。我想让图像在顶部,标题在底部,居中。这适用于以下代码:

- (void)centerAlignImageAndTextForButton:(UIButton*)button
{
    CGFloat spacing = 5;
    CGSize imageSize = button.imageView.frame.size;
    button.titleEdgeInsets = UIEdgeInsetsMake(0, -imageSize.width, -(imageSize.height + spacing), 0);
    CGSize titleSize = button.titleLabel.frame.size;
    button.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height + spacing), 0, 0, -titleSize.width);
}

但是,我注意到在进入此 View 之前有一点停顿。 Instruments 中的 Time Profiler 显示,花在 viewDidLoad 上的 99% 的时间是通过调用我的按钮方法引起的:

283.0ms  -[XViewController viewDidLoad]
282.0ms    -[XViewController centerAlignImageAndTextForButton:]
141.0ms      -[UIButton imageView]
 98.0ms        -[UIView(Hierarchy) layoutBelowIfNeeded]
141.0ms      -[UIButton titleLabel]
103.0ms        -[UIView(Hierarchy) layoutBelowIfNeeded]

[UIView(Hierarchy) layoutBelowIfNeeded] 中调用了各种与布局相关的东西,例如 [UIView(AdditionalLayoutSupport) recursiveLayoutEngineDidChange][NSLayoutConstraint addToEngine].

我知道可以在 Interface Builder 中设置这些插图,但这不仅是一项乏味的工作(需要“猜测”文本的宽度);该应用程序也将被本地化,因此适用于一种语言的插图不会适用于文本大小不同的另一种语言(我对 Storyboard和 .strings 文件使用基本本地化,而不是为每种语言复制整个 Storyboard).所以对我来说,以编程方式设置插图似乎是可行的方法,但它造成的延迟是 Not Acceptable 。

有什么想法可以解决这个问题吗?

最佳答案

将所有 centerAlignImageAndTextForButton 调用从 viewDidLoad 移动到 viewDidLayoutSubviews 将加载时间从之前的 283 毫秒减少到 18 毫秒(<1 毫秒 viewDidLoad 和 17 毫秒用于 viewDidLayoutSubviews)。

不过,我有点不解,为什么从viewDidLoad设置那些insets这么贵...

关于ios - 使用 Autolayout 设置 UIButton titleEdgeInsets 和 imageEdgeInsets 很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15430700/

相关文章:

ios - Xcode 7 中的建议完成问题

ios - 取消 iOS 订阅

ios - XMPP 我需要在特定的聊天对话中通过 XMPP Chat 发送打字状态

ios - UIButton 动画问题 - iOS

iphone - 为什么一个 UIButton 有 3 种不同的图像属性?

swift - 将 UIButton 标题设置为所有屏幕尺寸的特定位置

ios - 将 attributedText 分配给 UILabel 会使应用程序崩溃并返回 'NSConcreteMutableAttributedString initWithString::nil value'

iphone - iOS - MPMediaPickerController - 更改 barStyle

Objective-C菜鸟 : How to define + call a method in main?

ios - UIImageview 不显示图像