我有一个动态创建的按钮,需要调整大小.它有足够的空间来增长,但调用 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 调整为文本大小并保持漂亮的填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!