UIButton 字体大小没有变化


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中的标题为空。我成功地设置了标题。但字体大小没有改变。

在Xcode 13中,UIButton有四种类型:Plain,Grain,Tinted,Filled。当你在故事板中创建按钮时,按钮类型会自动设置为Plain,这意味着新的UIButton配置处于启用状态。如果你想改变旧的行为,你必须将样式plain设置为default

或者,如果你想要上面的样式之一。你需要设置类似的字体

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

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

遵循@Omer Tekbiyik答案注意,titleTextAttributesTransformerUIButton.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
}
UIConfigurationTextAttributesTransformer transformer;
transformer = ^(NSDictionary<NSAttributedStringKey, id> *incoming) {
NSMutableDictionary<NSAttributedStringKey, id> *outgoing = [incoming mutableCopy];
outgoing[NSFontAttributeName] = [UIFont systemFontOfSize:10];
return outgoing;
};
configuration.titleTextAttributesTransformer = transformer;

最新更新