问题
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
- Specify a
Frame
and useAdjustsFontSizeToFitWidth
- 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