【问题标题】:adjustsFontForContentSizeCategory is breaking the UIButtonadjustsFontForContentSizeCategory 正在破坏 UIButton
【发布时间】:2021-08-07 10:54:59
【问题描述】:

我有一个按钮,它配置了如下所示的扩展名:

extension UIButton {
   func applyStyle(_ type: CustomButtonType) {
        titleLabel?.adjustsFontForContentSizeCategory = true
        switch type {
        case .primary:
            backgroundColor = K.Colors.callToActionPrimary
            layer.cornerRadius = 10
            setTitleColor(UIColor.white, for: .normal)
        
        case .secondary:
            backgroundColor = UIColor.systemBackground
            layer.cornerRadius = 10
            layer.borderColor = K.Colors.callToActionPrimaryBorder?.cgColor
            layer.borderWidth = 1
            setTitleColor(K.Colors.callToActionPrimary, for: .normal)
        
        case .tertiary:
            backgroundColor = UIColor.systemBackground
            layer.cornerRadius = 10
            setTitleColor(K.Colors.callToActionPrimary, for: .normal)            
        }
    }
}

按钮设置顺序如下:

button1.applyStyle(.primary)
button1.setTitle("Some title", for: .normal)

虽然这适用于正常流程,但一旦我添加 UI 测试,setTitleColor() 似乎已损坏(或稍后执行)。

但是,如果我注释掉 titleLabel?.adjustsFontForContentSizeCategory = true 行,它可以在 UI 测试中使用。 为什么会坏掉?

【问题讨论】:

  • 显示按钮本身的代码。你如何设置标题?似乎问题在于调用函数的顺序。
  • @MojtabaHosseini 我通过编辑更新了问题,我包括了调用顺序请检查

标签: ios uibutton uikit swift5


【解决方案1】:

不知道为什么会发生这种情况,但我找到了解决方法。 我将有问题的代码行提取到单独的函数中,如下所示:

func allowAdjustFont() {
    titleLabel?.adjustsFontForContentSizeCategory = true
}

然后在代码中我按如下顺序调用它们:

actionButton.applyStyle(.primary)
actionButton.allowAdjustFont()

这似乎适用于正常的应用生命周期和屏幕截图测试。

【讨论】:

    猜你喜欢
    • 2018-01-16
    • 1970-01-01
    • 2016-07-02
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 2012-08-23
    • 2014-01-04
    相关资源
    最近更新 更多