【问题标题】:UIButton font size isn't changingUIButton 字体大小没有改变
【发布时间】:2022-09-24 16:54:12
【问题描述】:
private func updateViewFromModel() {
    for index in cardButtons.indices {
        let button = cardButtons[index]
        let card = game.cards[index]
        if card.isFaceUp {
            button.setTitle(emoji(for: card), for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 50)
            button.backgroundColor = .lightGray
        } else {
            button.setTitle(\"\", for: .normal)
            button.backgroundColor = card.isMatched ? .clear : .systemIndigo
        }
        
    }
}

谁能告诉我这段代码有什么问题? IB 中的标题为空。我成功设置了标题。但字体大小没有改变。

https://i.stack.imgur.com/lkLjp.png

  • 你的 XCode 版本是多少?

标签: swift uikit


【解决方案1】:

在 Xcode 13 中,UIButton 有四种类型是Plain,Grain,Tinted,Filled。当您在 storyboard 中创建按钮时,按钮类型会自动设置为 Plain,这意味着新的 UIButton 配置已打开。如果你想要旧的行为,你必须将样式plain 设置为default。

或者,如果您想要上述样式之一。您需要设置字体

button.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
  var outgoing = incoming
  outgoing.font = UIFont.systemFont(ofSize: 50)
  return outgoing
 }

【讨论】:

  • 最后,一个适用于最新 UIbutton 类型的适当答案。非常感谢。但似乎他们让它变得更复杂了。
【解决方案2】:
yourButton.titleLabel?.font =  UIFont(name: YourfontName, size: 20)

yourButton.titleLabel?.font = .systemFont(ofSize: 12)

我希望能帮助你;)

【讨论】:

    【解决方案3】:

    关注@Omer Tekbiyik 回答请注意,titleTextAttributesTransformer 是UIButton.Configuration 的参数,而不是UIButton,因此可能的实现是:

    var config = UIButton.Configuration.plain()
       config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
       var outgoing = incoming
       outgoing.font = UIFont(name: "AlmoniTzarAAA", size: 20) ?? .systemFont(ofSize: 20)
       return outgoing
    }
    

    【讨论】:

      【解决方案4】:

      只需在故事板中将按钮样式从普通更改为默认

      【讨论】:

        猜你喜欢
        • 2011-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多