首页 > 解决方案 > 如何使用滚动更改导航栏和 BarButtonItem 的颜色

问题描述

我想在向下滚动 TableView 时平滑地更改 UINavigationBar 和此 NavigationBar 内的 UIBarButtonItem 的背景颜色我在 AirBNB 应用程序中看到了这一点,但不知道如何做这样的事情。谢谢你的帮助

标签: swiftnavigationbar

解决方案


  1. 符合UIScrollViewDelegate并确保您的 tableView/CollectionView 委托设置为当前 ViewController。
  2. 实现scrollViewDidScroll(:)方法。
  3. 决定您首选的偏移量以更改 NavigationBarColor。
  4. 如果满足偏移条件,则更改 NavigationBarColor。

概括

Class UIViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
       let offset = scrollView.contentOffset.y
       if offset > 1 { // Or choose any desired offset
           // TODO:- Change your color for offset greater than 1
       }else {

             // TODO: - Change your nav bar for offset less than 1
       }
   }

}

推荐阅读