AdjustsFontSizeToFitWidth vs. SizeToFit

本小妞迷上赌 提交于 2019-12-10 11:29:29

问题


I'm using SizeToFit because I don't have to specify the Frame property to have an adaptive size of the UIButton/UILabel. In my case it's a button on a toolbar. Now I made the following observation:

If I use AdjustsFontSizeToFitWidth together with SizeToFit than the font size isn't adapted anymore. So I can

  1. Specify a Frame and use AdjustsFontSizeToFitWidth
  2. Use SizeToFit but don't have the adjustable font size anymore

Do you also have this problem? How do you circumvent this problem? How to let the intrinsic content size drive the frame size? Or do I have to set the Frame property? The advantage of Autolayout was to not define a frime size any more ...


回答1:


I think I made an error in reasoning. SizeToFit defines the size after the content (content has already a fixed size). AdjustsFontSizeToFitWidth needs a frame in which it can change the font size. Both together doesn't work.




回答2:


Here is a macro I've made to address this issue so that you can shrink font size to fit width AND call sizeToFit without the font size going back up post-shrink.

///Works like `adjustsFontSizeToFitWidth` but allows you to use `sizeToFit` and/or measure the new [adjusted] font size; one time adjustment, needs to be called again if `.text` changes.
#define shrinkFontSizeIfNeeded(__label) {\
UIFont *__currentFont = __label.font;\
CGFloat __originalFontSize = __currentFont.pointSize;\
CGSize __currentSize = [__label.text sizeWithAttributes:@{NSFontAttributeName : __currentFont}];\
while (__currentSize.width > __label.frame.size.width && __currentFont.pointSize > (__originalFontSize * __label.minimumScaleFactor)) {\
    __currentFont = [__currentFont fontWithSize:__currentFont.pointSize - 1];\
    __currentSize = [__label.text sizeWithAttributes:@{NSFontAttributeName : __currentFont}];\
}\
__label.font = __currentFont;\
}


来源:https://stackoverflow.com/questions/26019181/adjustsfontsizetofitwidth-vs-sizetofit

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