当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - Why UIButton's title content is abbreviated after calling [sizeToFit]?

问题描述:

I tried to fit UIButton to its title text by calling [SizeToFit]. Unfortunately, I got unwanted result as the following.

I suppose that the button's size is smaller than its title size. therefore, the title string was abbreviated. The simple and silly solution I chose was plus 20pt to its width after calling [sizeToFit].

I believe that there is any solution better than I used.

Is there anybody who know it?

网友答案:

sizeToFit does not resize the text but it is used to resize the view so it encloses its subviews. Please use adjustsFontSizeToFitWidth instead to resize font size to fit your button width.

btnMyButton.titleLabel.adjustsFontSizeToFitWidth = YES;

Or if you want to resize your button to fit the width of your font, here is how you can do that too:

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:btnMyButton.titleLabel.font, NSFontAttributeName, nil];
CGFloat buttonWidth = [[[NSAttributedString alloc] initWithString:btnMyButton.titleLabel.text attributes:attributes] size].width;

CGRect frame = btnMyButton.frame;
btnMyButton.frame = CGRectMake(frame.origin.x, frame.origin.y, buttonWidth, frame.size.width);

EDIT:

buttonWidth does give you the width your title requires to fit in, however if its still not working then please can you verify that:

1) Your button does not have any margins set, if it does then you might want to add those to your buttonWidth variable before setting btnMyButton.frame as:

buttonWidth += 10; //assuming you have 10pt margins.

2) Your button is not getting shrunk via an AutoLayout constraint or AutoResizingMask.

3) Your button is not getting font, size, or title set after btnMyButton.frame has been set.

4) Your button has enough room to resize.

分享给朋友:
您可能感兴趣的文章:
随机阅读: