【问题标题】:adjustsFontForContentSizeCategory not working for UITextView and UITextFieldadjustsFontForContentSizeCategory 不适用于 UITextView 和 UITextField
【发布时间】:2018-03-30 22:56:20
【问题描述】:

我正在从preferredContentSizeChanged 切换到adjustsFontForContentSizeCategory 用于我的UILabel、UITextView 和UITextField 课程。它适用于UILabel,但不适用于UITextView 和UITextField。仅当我在 preferredContentSizeChanged 中调用 setNeedsDisplay 时才有效。

我错过了什么?

【问题讨论】:

    标签: ios dynamic font-size


    【解决方案1】:

    正如 OliverD 所述,您必须将字体设置为自动调整大小的系统字体之一,同时设置adjustsFontForContentSizeCategory。这将调整文本大小,但不会调整文本字段/文本视图的整体大小。

    为此,您必须覆盖 traitCollectionDidChange 并在那里调整大小。

    例如,在设置视图时:

        self.intrinsicHeight = textInput.intrinsicContentSize.height
        self.heightConstraint = textInput.heightAnchor.constraint(equalToConstant: textField.intrinsicContentSize.height)
        self.heightConstraint?.isActive = true
    

    在您的视图或视图控制器中的其他地方:

    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        let fontMetrics = UIFontMetrics(forTextStyle: .body)
    
        self.heightConstraint.constant = fontMetrics.scaledValue(for: self.intrinsicHeight)
    }
    

    【讨论】:

      【解决方案2】:

      您还需要将 UITextfield 使用的字体设置为可缩放:

          textField.adjustsFontForContentSizeCategory = true
          textField.font = .preferredFont(forTextStyle: .body)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-07
        • 1970-01-01
        • 1970-01-01
        • 2012-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多