如何在xib中使用自定义TextStyle?

问题描述 投票:0回答:1

在代码中,我可以定义一个具有像这样的动态字体的 UILabel,并将此主体 TextStyle 字体从默认大小更改为 30。

label.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: UIFont.systemFont(ofSize: 30))

但是在 Xib 中,我只能使用默认的 body TextStyle 。 有什么方法可以更改 xib 中 body TextStyle 的默认配置吗?

ios types dynamic xib uifont
1个回答
0
投票

您可以通过自定义标签来实现这一点。我将使用

@IBDesignable
@IBInspectable
来更新 UI。

  1. 创建您自己的自定义
    label
@IBDesignable
class BodyTextStyleLabel: UILabel {
    @IBInspectable var bodyTextStyleFontSize: CGFloat = 30 {
        didSet {
            //Default is .body as you mentioned
            self.font = UIFontMetrics(forTextStyle: .body)
                .scaledFont(for: .systemFont(ofSize: bodyTextStyleFontSize))
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setup()
    }

    private func setup() {
        bodyTextStyleFontSize = 30
    }
}
  1. 在 XIB 文件中,将默认标签更改为上面定义的类:

enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.