UIButton titleLabel帧大小返回CGSize,零宽度和高度

sta*_*cnz 15 ios ios8

对于iOS7,我用的UIButton titleLabel.frame.size.width属性,以确定在不同的本地化我的按钮标题的宽度,这样我就可以将标题用正确contentInsetUIButton.

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

[space-x (image) space-y (titleLabel) space-x]
Run Code Online (Sandbox Code Playgroud)

在iOS 7和Xcode 5.1下,以下代码完美运行(甚至在XCode 5.1内置时在iOS 8 GM上运行):

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))];
Run Code Online (Sandbox Code Playgroud)

(18是图像的宽度,3是titleLabel上图中的图像和/ 或y 之间的间距数)

下的iOS 8和6的Xcode GM,button.titleLabel.frame.size返回一个CGSize具有零宽度及高度,所以我的contentInset结束了定心UIImageUIButton,引起titleLabel截断.

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

提前致谢!

小智 16

设置标题文本,然后为标题标签创建sizeToFit,并尝试获取titleLabel.frame.size.width

[myButton setTitle:@"My Title" forState:UIControlStateNormal];
[myButton.titleLabel sizeToFit];
Run Code Online (Sandbox Code Playgroud)


huy*_*ync 14

解决了 应用程序在运行iOS8上通过的Xcode 6建造,而不是更新的UIButton后右框架setTitle,setTitleEdgeInsets.它将等待下一次UI更新.所以,如果你得到titleLabel的框架,你将得到CGRectZero.

方案:

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

    [self setNeedsLayout];
    [self layoutIfNeeded];

要么:

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

要么:

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


mar*_*and 0

也许这对你不起作用,但我在 XCode 6 GM / iOS8 中运行代码时遇到了同样的问题,并且无法让它工作。它随机工作,我最终使用了不同的方法而不是 NSString 我使用 NSAttributedString 作为标题。

\n\n
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:@"Button text"];\nNSTextAttachment* textAttachment = [NSTextAttachment new];\ntextAttachment.image = [UIImage imageNamed:@"Arrows"];\nNSAttributedString *finalString = [NSAttributedString attributedStringWithAttachment:textAttachment];\n[attributedText appendAttributedString:finalString];\n
Run Code Online (Sandbox Code Playgroud)\n\n

唯一需要注意的是,它\xe2\x80\x99s iOS7 及更高版本,但似乎工作完美。

\n