导航栏标题与右侧按钮栏的Padding/Margin设置及标题截断问题
嘿,这个导航栏标题挤按钮的问题我之前也踩过坑!刚好有几个实用的方案能帮你解决标题和左右按钮之间的内边距问题,按需选就行:
方案一:自定义导航栏标题视图(最灵活可控)
直接自定义一个带内边距的标题标签,完全掌控标题的显示范围,这是我最常用的方法:
- 先写一个带内边距的
UILabel子类,让它自带左右padding - 把这个自定义标签设为导航栏的
titleView,就能保证标题和左右按钮始终有间距
示例代码:
// 自定义带内边距的Label class PaddingLabel: UILabel { // 可根据需求调整内边距数值 var textPadding = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16) override func drawText(in rect: CGRect) { super.drawText(in: rect.inset(by: textPadding)) } override var intrinsicContentSize: CGSize { let originalSize = super.intrinsicContentSize return CGSize( width: originalSize.width + textPadding.left + textPadding.right, height: originalSize.height + textPadding.top + textPadding.bottom ) } } // 在ViewController中设置标题 let customTitleLabel = PaddingLabel() customTitleLabel.text = "从服务器获取的超长标题内容示例" customTitleLabel.textAlignment = .center customTitleLabel.font = UIFont.systemFont(ofSize: 17, weight: .semibold) customTitleLabel.textColor = .label customTitleLabel.numberOfLines = 1 customTitleLabel.lineBreakMode = .byTruncatingTail navigationItem.titleView = customTitleLabel
这样不管标题长短,都会在你设置的内边距范围内显示,过长时会自动截断,不会和左右按钮挤在一起。
方案二:调整导航栏全局布局边距(iOS 11+)
如果想让整个导航栏的内容(包括按钮和标题)都统一缩进,可以调整导航栏的布局边距:
if let navBar = navigationController?.navigationBar { // 调整左右边距为16pt,可按需修改 navBar.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16) navBar.layoutIfNeeded() }
这个方法会让返回按钮、右侧Logout按钮和标题一起往内缩,适合想要整体风格统一的场景,缺点是会影响所有导航栏内容的位置。
方案三:给左右按钮单独加内边距
如果不想改动标题的默认样式,也可以给返回按钮和Logout按钮本身添加内边距,间接给标题腾出空间:
// 自定义返回按钮(带内边距) let backBtn = UIButton(type: .system) backBtn.setImage(UIImage(systemName: "arrow.left"), for: .normal) backBtn.setTitle("返回", for: .normal) // 调整按钮内部图文间距和整体边距 backBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8) backBtn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0) backBtn.addTarget(self, action: #selector(backTapped), for: .touchUpInside) navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn) // 自定义Logout按钮(带内边距) let logoutBtn = UIButton(type: .system) logoutBtn.setTitle("Logout", for: .normal) logoutBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16) logoutBtn.addTarget(self, action: #selector(logoutTapped), for: .touchUpInside) navigationItem.rightBarButtonItem = UIBarButtonItem(customView: logoutBtn)
这种方法适合只想微调按钮和标题间距的场景,标题还是用系统默认的渲染逻辑。
内容的提问来源于stack exchange,提问作者Android teem
相关产品推荐
相关产品推荐

