NavigationBar下拉覆盖自定义按钮,求实现按钮随导航栏联动方案
解决大标题导航栏下拉时自定义按钮同步跟随的问题
针对大标题导航栏下拉收缩时自定义按钮被覆盖的问题,提供三种可行方案:
方案一:将按钮添加为导航栏子视图(直接跟随)
把自定义按钮作为导航栏的子视图,利用导航栏自身的frame变化自动同步位置:
override func viewDidLoad() { super.viewDidLoad() // 创建自定义按钮 let customButton = UIButton(type: .system) customButton.setTitle("自定义按钮", for: .normal) customButton.sizeToFit() // 添加到导航栏 navigationController?.navigationBar.addSubview(customButton) // 设置约束,保持和导航栏右侧、垂直居中对齐 customButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ customButton.trailingAnchor.constraint(equalTo: navigationController!.navigationBar.trailingAnchor, constant: -16), customButton.centerYAnchor.constraint(equalTo: navigationController!.navigationBar.centerYAnchor) ]) // 开启大标题模式 navigationItem.largeTitleDisplayMode = .always navigationController?.navigationBar.prefersLargeTitles = true }
方案二:监听滚动视图,实时更新按钮位置
如果按钮必须添加在控制器view上,通过监听TableView滚动,同步调整按钮frame:
var customButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // 初始化按钮并添加到view customButton = UIButton(type: .system) customButton.setTitle("自定义按钮", for: .normal) customButton.sizeToFit() view.addSubview(customButton) // 初始布局 updateButtonPosition() // 监听滚动 tableView.delegate = self navigationItem.largeTitleDisplayMode = .always navigationController?.navigationBar.prefersLargeTitles = true } // 更新按钮位置的方法 private func updateButtonPosition() { guard let navBar = navigationController?.navigationBar else { return } customButton.frame = CGRect( x: navBar.frame.maxX - customButton.bounds.width - 16, y: navBar.frame.midY - customButton.bounds.height / 2, width: customButton.bounds.width, height: customButton.bounds.height ) } // 实现滚动代理 extension ViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { updateButtonPosition() } }
方案三:使用系统导航栏右侧按钮(推荐)
如果按钮功能适合作为导航栏操作按钮,直接利用系统的rightBarButtonItem,系统会自动处理跟随逻辑:
override func viewDidLoad() { super.viewDidLoad() let customButton = UIButton(type: .system) customButton.setTitle("自定义按钮", for: .normal) customButton.sizeToFit() // 包装成UIBarButtonItem let barButton = UIBarButtonItem(customView: customButton) navigationItem.rightBarButtonItem = barButton // 开启大标题模式 navigationItem.largeTitleDisplayMode = .always navigationController?.navigationBar.prefersLargeTitles = true }
内容的提问来源于stack exchange,提问作者Smitha
相关产品推荐
相关产品推荐

