iOS: UIButton resize according to text length

后端 未结 14 931
你的背包
你的背包 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:17

    In UIKit, there are additions to the NSString class to get from a given NSString object the size it'll take up when rendered in a certain font.

    Docs was here. Now it's here under Deprecated.

    In short, if you go:

    CGSize stringsize = [myString sizeWithFont:[UIFont systemFontOfSize:14]]; 
    //or whatever font you're using
    [button setFrame:CGRectMake(10,0,stringsize.width, stringsize.height)];
    

    ...you'll have set the button's frame to the height and width of the string you're rendering.

    You'll probably want to experiment with some buffer space around that CGSize, but you'll be starting in the right place.

提交回复
热议问题