iOS:UIButton根据文本长度调整大小 [英] iOS: UIButton resize according to text length
本文介绍了iOS:UIButton根据文本长度调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在界面构建器中,按住 Command + = 将调整按钮的大小以适合其文本。我想知道在按钮添加到视图之前是否可以以编程方式执行此操作。
In interface builder, holding Command + = will resize a button to fit its text. I was wondering if this was possible to do programmatically before the button was added to the view.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12]];
[button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
// I need to know the width needed to accomodate NSStringVariable
[button setTitle:NSStringVariable forState:UIControlStateNormal];
// So that I can set the width property of the button before addSubview
[button setFrame:CGRectMake(10, 0, width, fixedHeight)];
[subNavigation addSubview:button];
推荐答案
在Xcode 4.5及以上版本中,现在可以完成使用'自动布局/约束'。
In Xcode 4.5 and above, this can now be done by using 'Auto-layouting / Constraints'.
主要优点是:
- 您根本不需要以编程方式设置帧!
- 如果操作正确,您无需为重置方向而重置帧。
- 此外,设备更改无需打扰您(阅读,无需针对不同的屏幕尺寸单独编码)。
一些缺点:
- 不向后兼容 - 仅适用于iOS 6及更高版本。
- 需要熟悉(但以后会节省时间)。
最酷的事情是我们专注于声明一个意图如下:
Coolest thing is we get to focus on declaring an intent such as:
- 我希望这两个按钮具有相同的宽度;或
- 我需要将此视图垂直居中,并从superview的边缘延伸到最大10 pts;甚至,
- 我希望这个按钮/标签根据它显示的标签调整大小!
这里是一个简单的教程引入自动布局。
Here is a simple tutorial to get introduced to auto-layouting.
对于更多细节。
一开始需要一些时间,但看起来确实值得付出努力。
It takes some time at first, but it sure looks like it will be well worth the effort.
这篇关于iOS:UIButton根据文本长度调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文