AdjustsFontSizeToFitWidth与SizeToFit

时间:2014-09-24 14:14:33

标签: ios uiview sizetofit

我正在使用SizeToFit,因为我不必指定Frame属性,使其具有UIButton / UILabel的自适应大小。就我而言,它是工具栏上的一个按钮。现在我做了以下观察:

如果我将AdjustsFontSizeToFitWidthSizeToFit一起使用,则字体大小将不再适应。所以我可以

  1. 指定Frame并使用AdjustsFontSizeToFitWidth
  2. 使用SizeToFit但不再具有可调整的字体大小
  3. 你也有这个问题吗?你如何规避这个问题?如何让内在的内容大小驱动帧大小?或者我是否必须设置Frame属性? Autolayout的优点是不再定义一个frime大小......

2 个答案:

答案 0 :(得分:1)

我认为我在推理中犯了一个错误。 SizeToFit定义内容后的大小(内容已经是固定大小)。 AdjustsFontSizeToFitWidth需要一个可以更改字体大小的框架。两者都不起作用。

答案 1 :(得分:0)

这是我为解决此问题而制作的宏,以便您可以缩小字体大小以适合宽度并调用sizeToFit,而字体大小不会在收缩后返回。

///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;\
}