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 调整为文本大小并保持漂亮的填充?
基础教程推荐
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01