如何以编程方式调整UIButton的文本大小,并保持一个很好的填充?

我有一个dynamic创build的button,需要resize。 它有足够的空间增长,但调用sizeToFit接缝什么也不做,或者至less不足以放大button。

我如何获得预期的效果?

查看NSString方法-sizeWithFont: 它会返回一个CGSize ,告诉你文本在button中需要多大的尺寸。 然后,您可以根据此大小调整button的框架,将所需的任何填充添加到button框架的宽度和高度。 像这样的东西:

 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; 

(从内存写入;不编译。:-)

当然,你必须设置button标题和字体以及…

在iOS 7中,sizeWithFont:被折旧。 现在你应该使用sizeWithAttribute :.

但是,这不是我将如何解决这个问题。 有两种方法可以解决这个问题:

1)要使用[button sizeToFit]确保AutoLayout被禁用。 否则,您将无法以编程方式调整button的大小。 你将不得不调整你的约束的大小。

2)但是,这个答案在使用上是非常有限的。 在我要示范的例子中,button将会从屏幕上消失,因为文本全部在一行上。 要在限制宽度的同时更改button的高度,请使用以下代码。 再次确保自动布局被closures或这将无法正常工作。

  UIFont *font = [UIFont fontWithName:@"Helvetica-Bold" size:14.0]; NSString *text = @"This is a very long new title for the button to be sure, now I'm going to add even more"; [self.testButton setTitle:text forState:UIControlStateNormal]; self.testButton.titleLabel.font = font; CGFloat width = self.testButton.frame.size.width - 10; //button width - padding width NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: font}]; CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX} options:NSStringDrawingUsesLineFragmentOrigin context:nil]; CGSize size = rect.size; size.height = ceilf(size.height); size.width = ceilf(size.width); self.testButton.frame = CGRectMake(self.testButton.frame.origin.x, self.testButton.frame.origin.y, self.testButton.frame.size.width, size.height + 15); 

因为boundingRectWithSize会传递给你一个非整数大小的矩形,所以你必须使用ceilf来取整。

在将其传递到boundingRectWithSize以创build我的button的填充之前,我从宽度中减去10。