【问题标题】:AdjustsFontSizeToFitWidth vs. SizeToFitAdjustsFontSizeToFitWidth 与 SizeToFit
【发布时间】:2014-11-19 01:57:11
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: ios uiview sizetofit


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      这是我为解决此问题而制作的一个宏,以便您可以缩小字体大小以适应宽度并调用 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;\
      }
      

      【讨论】:

        猜你喜欢
        • 2016-09-13
        • 2014-05-01
        • 1970-01-01
        • 2020-08-09
        • 1970-01-01
        • 1970-01-01
        • 2012-10-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多