Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

iphone - How to programmatically resize an UIButton to the text size and keep a nice padding?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...