iOS: UIButton resize according to text length

后端 未结 14 834
你的背包
你的背包 2020-11-29 17:28

In interface builder, holding Command + = will resize a button to fit its text. I was wondering if this was possible to do programmatically before the

14条回答
  •  独厮守ぢ
    2020-11-29 18:05

    I have some additional needs related to this post that sizeToFit does not solve. I needed to keep the button centered in it's original location, regardless of the text. I also never want the button to be larger than its original size.

    So, I layout the button for its maximum size, save that size in the Controller and use the following method to size the button when the text changes:

    + (void) sizeButtonToText:(UIButton *)button availableSize:(CGSize)availableSize padding:(UIEdgeInsets)padding {    
    
         CGRect boundsForText = button.frame;
    
        // Measures string
        CGSize stringSize = [button.titleLabel.text sizeWithFont:button.titleLabel.font];
        stringSize.width = MIN(stringSize.width + padding.left + padding.right, availableSize.width);
    
        // Center's location of button
        boundsForText.origin.x += (boundsForText.size.width - stringSize.width) / 2;
        boundsForText.size.width = stringSize.width;
        [button setFrame:boundsForText];
     }
    

提交回复
热议问题