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

如何通过UIButton.Configuration给按钮标题加下划线?为何代码无效果?

UIButton下划线标题不显示的解决办法

你写的UIButton便利初始化代码如下:

convenience init(underlinedTitle: String, font: UIFont, color: UIColor) {
    var configuration = UIButton.Configuration.plain()
    configuration.title = underlinedTitle
    configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
        var outgoing = incoming
        outgoing.font = font
        outgoing.foregroundColor = color
        outgoing.underlineStyle = .single
        outgoing.underlineColor = color
        return outgoing
    }
    self.init(configuration: configuration)
}

实际效果:
效果展示图

问题原因

在iOS 15+推出的UIButton Configuration API中,titleTextAttributesTransformer主要用于统一转换文本基础属性,下划线这类富文本样式通过该转换器设置时,plain配置的按钮无法正确识别并渲染该属性。

解决办法

直接创建带下划线的富文本标题,赋值给Configuration的attributedTitle属性,修改后的代码如下:

convenience init(underlinedTitle: String, font: UIFont, color: UIColor) {
    var configuration = UIButton.Configuration.plain()
    // 构建富文本属性字典
    let attrDict: [NSAttributedString.Key: Any] = [
        .font: font,
        .foregroundColor: color,
        .underlineStyle: NSUnderlineStyle.single.rawValue,
        .underlineColor: color
    ]
    // 将普通文本转为带样式的富文本
    configuration.attributedTitle = AttributedString(NSAttributedString(string: underlinedTitle, attributes: attrDict))
    self.init(configuration: configuration)
}

这样修改后,按钮标题的下划线就能正常显示了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 02:56:05