Change font size to fit text inside button entirely?

佐手、 提交于 2019-12-11 01:47:30

问题


I'm trying to fit the letter '6' inside a UIButton so that the font automatically scales down when the program is run on a small screen device, such that the letter 6 is inside from all sides.

I found several other threads offering solutions to the same problem but for some reason they don't work for me. A few threads I found were:

  • how do i let text fit to UIButton?

  • Adjust font size of text to fit in UIButton

  • Auto change the font size to fit the button in swift

I have tried the following two code sequences but none gets the job done:

What should I do ?

1:

self.sixButton.titleLabel!.numberOfLines = 0;
self.sixButton.titleLabel!.adjustsFontSizeToFitWidth = true;
self.sixButton.titleLabel!.lineBreakMode = NSLineBreakMode.ByWordWrapping

2:

self.sixButton.titleLabel!.minimumScaleFactor = 0.5;
self.sixButton.titleLabel!.numberOfLines = 0;
self.sixButton.titleLabel!.adjustsFontSizeToFitWidth = true;

3: Same as above but with self.sixButton.titleLabel!.numberOfLines = 1;.

I'm using Swift 2.2 with Xcode 7.3.1.

A picture of the button at design time:

A picture of the button at run time:


回答1:


What I would do is measure the size of the "6" in successively smaller font sizes until we get to a size that fits in the desired bounds, and use that size.




回答2:


My solution to this would be to have a label and an invisible button that work together. The invisible button sits on top of the label. The behaviour of text in a label is more flexible and predictable than that of a button in my experience. This probably isn't the cleverest or slickest solution, but it works great and it's painless to implement. You just need to ensure that your constraints keep the button and label aligned.



来源:https://stackoverflow.com/questions/38494183/change-font-size-to-fit-text-inside-button-entirely

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!