如何通过代码调整开启prefersLargeTitles的UIBarButtonItem位置?
问题解决:大标题模式下导航栏右侧按钮与标题对齐
当开启prefersLargeTitles = true后,系统默认会让右侧按钮对齐大标题的底部,想要让它和标题文字中心对齐,你可以试试以下几种方案:
方案一:自定义按钮并通过约束控制位置(最灵活)
系统的UIBarButtonItem布局由导航栏管理,直接修改属性容易被覆盖,用自定义UIButton作为customView可以完全控制位置:
private func settingNavigationBar() { title = "MoneyCount" navigationController?.navigationBar.prefersLargeTitles = true let plusButton = UIButton(type: .system) plusButton.setImage(UIImage(systemName: "plus.circle"), for: .normal) plusButton.addTarget(self, action: #selector(pressedPlusButton), for: .touchUpInside) plusButton.translatesAutoresizingMaskIntoConstraints = false // 将按钮中心Y与导航栏中心Y对齐 if let navigationBar = navigationController?.navigationBar { NSLayoutConstraint.activate([ plusButton.centerYAnchor.constraint(equalTo: navigationBar.centerYAnchor) ]) } navigationItem.rightBarButtonItem = UIBarButtonItem(customView: plusButton) } @objc private func pressedPlusButton() { // 你的点击逻辑 }
方案二:调整按钮图片内边距(快速生效)
直接给系统UIBarButtonItem设置imageInsets,向上偏移按钮位置,数值可以根据设备微调:
private func settingNavigationBar() { title = "MoneyCount" navigationController?.navigationBar.prefersLargeTitles = true let barButton = UIBarButtonItem(image: UIImage(systemName: "plus.circle"), style: .plain, target: self, action: #selector(pressedPlusButton)) // 向上偏移16pt,可根据实际显示效果调整 barButton.imageInsets = UIEdgeInsets(top: -16, left: 0, bottom: 0, right: 0) navigationItem.rightBarButtonItem = barButton } @objc private func pressedPlusButton() { // 你的点击逻辑 }
方案三:通过导航栏外观统一配置(全局生效)
如果需要所有页面的大标题模式按钮都对齐,可以用UINavigationBarAppearance统一设置:
private func settingNavigationBar() { title = "MoneyCount" let largeTitleAppearance = UINavigationBarAppearance() // 调整按钮图片的垂直偏移 largeTitleAppearance.buttonAppearance.normal.imagePositionAdjustment = UIOffset(horizontal: 0, vertical: -16) navigationController?.navigationBar.prefersLargeTitles = true navigationController?.navigationBar.standardAppearance = largeTitleAppearance navigationController?.navigationBar.scrollEdgeAppearance = largeTitleAppearance navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "plus.circle"), style: .plain, target: self, action: #selector(pressedPlusButton)) } @objc private func pressedPlusButton() { // 你的点击逻辑 }
注意点
直接修改rightBarButtonItem的frame或者导航栏的frame不会生效,因为导航栏的布局由系统自动管理,以上几种方式都是通过系统允许的配置入口来调整位置,避免被系统布局覆盖。
内容的提问来源于stack exchange,提问作者CT4TuEI3
相关产品推荐
相关产品推荐

