UIButton titleLabel框架大小返回CGSize与零宽度和高度

对于iOS7,我使用UIButton titleLabel.frame.size.width属性来确定我的button标题在不同的本地化下的宽度,所以我可以使用UIButton上的contentInset正确定位标题。

我的UIButton设置了图像和标题,我总是希望这两个组合在UIButton水平居中,例如:

 [space-x (image) space-y (titleLabel) space-x] 

在iOS 7和Xcode 5.1下,以下代码完美运行(即使在iOS 8 GM中运行时,也可以在XCode 5.1中运行):

 CGSize buttonSize = button.frame.size; CGSize titleSize = button.titleLabel.frame.size; float contentInset =((buttonSize.width - (titleSize.width + 18 + 3)) / 2 ); float contentInsetRounded = roundf(contentInset); [button setContentEdgeInsets:(UIEdgeInsetsMake(0, contentInsetRounded, 0, 0))]; 

(18是图像的宽度,3是图像和titleLabel或space-y之间的点间隔数,在我上面的例子中)

在iOS 8和Xcode 6 GM下, button.titleLabel.frame.size返回一个宽度和高度为零的CGSize ,所以我的contentInset最终将UIImage居中在UIButton ,导致titleLabel被截断。

有任何想法吗? 我试图在这个代码之前立即设置titleLabel文本,以防它认为它是空的,但也没有帮助。

提前致谢!

解决了它。 应用程序在iOS8上运行,由Xcode 6构build,而不是在UIButton setTitlesetTitleEdgeInsets之后更新框架。 它将等待下一个UI更新。 所以,如果你得到titleLabel的框架,你会得到CGRectZero。

解答

  1. 设置UI属性后调用下面的方法,立即更新布局:

    [self setNeedsLayout];
    [self layoutIfNeeded];

要么:

  1. 延迟一秒,你可以得到titleFrame ,使用self.titleLabel.frame

要么:

  1. 主队列中的dispatch_async,将代码移动到下一个队列

设置标题文本,然后为标题标签制作一个sizeToFit,并尝试获取titleLabel.frame.size.width

 [myButton setTitle:@"My Title" forState:UIControlStateNormal]; [myButton.titleLabel sizeToFit]; 

如果您在获取框架后在button旁边设置图像,则可以使用

 [theButton setTitle: @"theTitle" forState:UIControlStateNormal]; [theButton setImage: theImage forState:UIControlStateNormal]; [theButton setNeedsLayout]; [theButton layoutIfNeeded]; [theButton setImageEdgeInsets: UIEdgeInsetsMake(6, transactionsButton.titleLabel.frame.size.width + 40.0, 0, 0)]; 

而在Swift 3中,这样做会的。

 self.view.layoutIfNeeded() 

也许这不适合你,但是在XCode 6 GM / iOS8中运行我的代码时遇到了同样的问题,无法使其工作。 它随机工作,我结束了使用一种不同的方法,而不是一个NSString我用一个NSAttributedString作为标题。

 NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:@"Button text"]; NSTextAttachment* textAttachment = [NSTextAttachment new]; textAttachment.image = [UIImage imageNamed:@"Arrows"]; NSAttributedString *finalString = [NSAttributedString attributedStringWithAttachment:textAttachment]; [attributedText appendAttributedString:finalString]; 

唯一需要注意的是它是iOS7以上,但似乎工作完美无瑕。

事实certificate,我已经把自己陷入了这个问题。 我拿出了所有我的内容embedded代码,因此不需要findframe.size。 我现在只是中心的button标题,一切都很好!

仍然似乎有一个frame.size的问题,但为了我的需要,我可以解决它。