相关疑难解决方法(0)

UIButton调整大小以适应其titleLabel

我有一个UIButton我在故事板中添加到我的视图控制器的视图.我添加居中约束来定位它并引导空间约束以限制其宽度.在代码中我添加:

self.button.titleLabel.numberOfLines = 0;
self.button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
[self.button setTitle:@"A real real real real real real real real long long name." forState:UIControlStateNormal];
self.button.backgroundColor = [UIColor redColor];
self.button.titleLabel.backgroundColor = [UIColor blueColor];
Run Code Online (Sandbox Code Playgroud)

结果如下所示:

在此输入图像描述

我希望按钮的大小适合其内容.我怎样才能做到这一点?

我试过了

[self.button sizeToFit];
Run Code Online (Sandbox Code Playgroud)

我已经尝试将内容拥抱和压缩阻力自动布局约束优先级设置为所需.

我也试过明确设置contentEdgeInsetstitleEdgeInsetsto UIEdgeInsetsZero和调用invalidateIntrinsicContentSize.

我还注意到,如果我在标题字符串中放置换行符,那么按钮似乎会调整大小以适应其内容.

我在iPhone 6模拟器上运行Xcode 6和iOS 8.

uibutton uilabel ios autolayout

34
推荐指数
4
解决办法
3万
查看次数

标签 统计

autolayout ×1

ios ×1

uibutton ×1

uilabel ×1