You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么调用UIButton的setTitle方法会改变按钮的字体大小?

问题原因

该问题出现在iOS 15及以上版本,系统为UIButton默认启用了UIButton.Configuration样式配置机制:当你调用setTitle(_:for:)方法修改按钮标题时,系统会自动触发默认配置的样式更新,覆盖你在Storyboard中自定义的字体字号。你打印得到的30号是titleLabel属性中未被同步的旧值,实际页面渲染时优先使用configuration中的默认17号系统字体,所以出现显示字号和打印值不一致的情况。

解决方案

你可以任选以下任意一种方案解决:

  • 方案1:修改按钮Configuration配置(推荐适配新版本)
    调整toggleEditingMode中的代码,直接修改configuration的标题属性并显式指定字体,避免样式被重置:

    @IBAction func toggleEditingMode(_ sender: UIButton) {
        setEditing(!isEditing, animated: true)
        if var config = sender.configuration {
            config.title = isEditing ? "Done" : "Edit"
            // 字体设置和你Storyboard中配置的保持一致即可
            config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
                var updatedAttributes = attributes
                updatedAttributes.font = .systemFont(ofSize: 30)
                return updatedAttributes
            }
            sender.configuration = config
        } else {
            // 兼容iOS 15以下版本
            sender.setTitle(isEditing ? "Done" : "Edit", for: .normal)
        }
    }
    
  • 方案2:修改按钮类型为Custom(无代码改动)
    打开Storyboard,选中你的Edit按钮,在属性检查器(Attributes Inspector)中将按钮的Type从System修改为Custom,原有代码不需要任何改动,修改标题时就不会自动重置字体样式。

  • 方案3:使用富文本设置标题
    替换原有setTitle调用为富文本设置,强制指定字体样式:

    let buttonTitle = isEditing ? "Done" : "Edit"
    sender.setAttributedTitle(
        NSAttributedString(string: buttonTitle, attributes: [.font: UIFont.systemFont(ofSize: 30)]),
        for: .normal
    )
    

内容的提问来源于stack exchange,提问作者Lexi Reinsborough

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 06:39:00