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

iOS15+ UIButtonConfiguration下标题单行截断失效问题求助

iOS 15+ UIButtonConfiguration 标题单行截断问题解决

问题场景

使用UIButtonConfiguration控制UIButton样式时,设置过长标题与固定宽高约束后,标题无法实现iOS15之前默认的单行尾部截断效果。尝试直接修改titleLabel的numberOfLines和lineBreakMode属性无作用。

相关代码

按钮初始化代码

private lazy var button: UIButton = {
    let btn = UIButton()

    self.view.addSubview(btn)

    if #available(iOS 15.0, *) {
        var configuration = UIButton.Configuration.plain()
        configuration.contentInsets = NSDirectionalEdgeInsets(top: 1.0, leading: 12.0, bottom: 1.0, trailing: 12.0)
        configuration.imagePadding = 12.0
        btn.configuration = configuration
    } else {
        btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -12, bottom: 0, right: 0)
        btn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 0)
    }

    btn.translatesAutoresizingMaskIntoConstraints = false

    return btn
}()

标题与约束设置

self.button.setTitle("DoneDoneDoneDoneDoneDoneDoneDoneDoneDoneDoneDoneDoneDoneDoneDone", for: .normal)

NSLayoutConstraint.activate([
    self.button.heightAnchor.constraint(equalToConstant: 32.0),
    self.button.widthAnchor.constraint(equalToConstant: 96.0),
    self.button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
    self.button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
])

解决方法

在iOS15+的UIButtonConfiguration配置逻辑中,需直接为配置对象指定标题换行模式,同时强制titleLabel单行显示,修改后的iOS15适配代码如下:

if #available(iOS 15.0, *) {
    var configuration = UIButton.Configuration.plain()
    configuration.contentInsets = NSDirectionalEdgeInsets(top: 1.0, leading: 12.0, bottom: 1.0, trailing: 12.0)
    configuration.imagePadding = 12.0
    // 配置标题尾部截断
    configuration.titleLineBreakMode = .byTruncatingTail
    btn.configuration = configuration
    // 强制标题单行显示
    btn.titleLabel?.numberOfLines = 1
}

关键说明

UIButtonConfiguration会接管titleLabel的部分样式控制,仅修改titleLabel属性无法覆盖配置的默认行为,必须在配置对象中显式设置titleLineBreakMode才能生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 22:20:32