2

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

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

  1. 指定一个Frame并使用AdjustsFontSizeToFitWidth
  2. 使用SizeToFit但不再有可调整的字体大小

你也有这个问题吗?你如何规避这个问题?如何让内在内容大小驱动帧大小?还是我必须设置Frame属性?Autolayout 的优点是不再定义边框大小......

4

2 回答 2

3

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

于 2014-09-24T14:54:07.053 回答
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;\
}
于 2018-07-23T06:52:44.623 回答