导航栏标题按钮文本无法尾部截断问题求助
解决导航栏标题按钮长文本截断问题
1. 强制标题按钮文本尾部截断
给TitleButton配置文本截断规则和布局优先级,避免长文本挤压其他按钮:
// 设置文本尾部截断模式 TitleButton.titleLabel?.lineBreakMode = .byTruncatingTail // 禁止文本自动缩小适配宽度 TitleButton.titleLabel?.adjustsFontSizeToFitWidth = false // 降低标题按钮的水平压缩抵抗优先级,让它优先被压缩,而非挤掉其他按钮 TitleButton.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) // 给菜单、搜索按钮设置更高的压缩抵抗优先级,确保它们不会被挤压消失 menuButton.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) searchButton.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
2. 修复代码设置文本后的样式异常
直接调用setTitle会覆盖Storyboard中配置的样式,可通过富文本保留原有样式:
if let originalAttrs = TitleButton.titleLabel?.attributedTitle?.attributes(at: 0, effectiveRange: nil) { let uppercasedText = titleString.uppercased() let attrText = NSAttributedString(string: uppercasedText, attributes: originalAttrs) TitleButton.setAttributedTitle(attrText, for: .normal) } else { // 若没有原有富文本属性,手动恢复Storyboard里的样式配置 TitleButton.setTitle(titleString.uppercased(), for: .normal) // 示例:还原字体、颜色,根据你的实际配置调整 TitleButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium) TitleButton.setTitleColor(.darkText, for: .normal) }
3. 优化导航栏左侧容器布局
如果三个按钮是放在自定义视图中作为导航栏左侧项,需确保布局约束合理:
- 容器视图与导航栏的
leading、top、bottom绑定约束 - 三个按钮之间设置固定间距
- 给标题按钮设置宽度最大值约束,或降低宽度约束的优先级
内容的提问来源于stack exchange,提问作者Muvenda Terrence
相关产品推荐
相关产品推荐

