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

iOS 15新按钮配置下修改标题字体变更,求解决方案

解决iOS 15按钮配置修改标题后字体变更的问题

直接修改configuration.title后字体被重置,是因为系统会默认使用按钮配置的默认文本样式覆盖自定义字体。以下两种方法可以解决这个问题,同时保留iOS 15的新按钮样式:

方法一:修改标题后重新指定字体属性

通过titleTextAttributesTransformer保留或设置自定义字体,确保修改标题后样式不丢失:

guard var config = btnNext.configuration else { return }
// 修改标题文本
config.title = "New Title"
// 自定义字体样式,替换为你需要的字体参数
config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
    var updatedAttributes = incoming
    updatedAttributes.font = UIFont.systemFont(ofSize: 16, weight: .medium)
    // 可按需添加其他样式,比如颜色
    // updatedAttributes.foregroundColor = UIColor.systemBlue
    return updatedAttributes
}
// 更新按钮配置
btnNext.configuration = config

如果需要保留按钮原本的字体样式,可以先保存原属性再复用:

guard var config = btnNext.configuration else { return }
// 保存原标题文本属性
let originalTextAttributes = config.titleTextAttributesTransformer?.transform([:]) ?? [:]
// 修改标题
config.title = "New Title"
// 重新应用原样式
config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { _ in
    return originalTextAttributes
}
btnNext.configuration = config

方法二:使用富文本标题设置

直接给配置的attributedTitle赋值,通过富文本明确指定字体,避免系统重置样式:

guard var config = btnNext.configuration else { return }
// 创建带自定义字体的富文本
let attributedTitle = NSAttributedString(
    string: "New Title",
    attributes: [
        .font: UIFont.systemFont(ofSize: 16, weight: .medium),
        .foregroundColor: UIColor.systemBlue // 按需设置颜色
    ]
)
// 将NSAttributedString转为AttributedString赋值给配置
config.attributedTitle = AttributedString(attributedTitle)
btnNext.configuration = config

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:35:31