How to programmatically resize an UIButton to the text size and keep a nice padding?(如何以编程方式将 UIButton 调整为文本大小并保持漂亮的填充?)
问题描述
我有一个动态创建的按钮,需要调整大小.它有足够的空间来增长,但调用 sizeToFit 接缝什么也不做,或者至少没有足够放大按钮.
I have a button that is created dynamically and needs to be resized. It has plenty of space where to grow but calling sizeToFit seams to do nothing or at least not enlarging the button enough.
如何才能获得想要的效果?
How can I obtain the desired effect?
推荐答案
查看 NSString
方法 -sizeWithFont:
.它返回一个 CGSize
,它将通知您按钮中的文本需要多大的大小.然后,您可以根据此大小调整按钮的框架,将您想要的任何填充添加到按钮框架的宽度和高度.像这样的:
Check out the NSString
method -sizeWithFont:
. It returns a CGSize
that will inform you as to how much size your text will need in the button. Then you can adjust the button's frame based on this size, adding whatever padding you desire to the width and height of the button's frame. Something like this:
NSString *msg = @"The button label";
UIFont *font = [UIFont systemFontOfSize:17];
CGSize msgSize = [msg sizeWithFont:font];
CGRect frame = button.frame;
frame.size.width = msg.size.width+10;
frame.size.height = msg.size.height+10;
button.frame = frame;
(从内存中写入;未编译.:-)
(written from memory; not compiled. :-)
当然,你还要设置按钮的标题和字体……
Of course, you have to set the button title and font as well...
这篇关于如何以编程方式将 UIButton 调整为文本大小并保持漂亮的填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何以编程方式将 UIButton 调整为文本大小并保持漂亮的填充?
- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- GPS状态的广播接收器? 2022-01-01
- UITextView 内容插图 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01
- 网上有没有好的 UIScrollView 教程? 2022-01-01
- URL编码Swift iOS 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01