如何以编程方式将UIButton的大小调整为文本大小并保持一个漂亮的填充? [英] How to programmatically resize an UIButton to the text size and keep a nice padding?

查看:130
本文介绍了如何以编程方式将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的大小调整为文本大小并保持一个漂亮的填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆