当用户在 table 视图中向下滚动时,如何将 UINavigationBar 背景颜色从透明更改为红色

How to change UINavigationBar background color from clear to red when user scrolls down in the table view

我有一个 table 视图和它前面的导航栏。 我希望当用户向下滚动时,导航栏的背景颜色开始从透明变为红色,就像增加 alpha 一样。

我的问题是,当用户向下滚动时,当导航栏背景 alpha 为 1.0 时,用户仍然可以看到导航栏后面!

这是我的代码:

override func viewDidLoad() {
    super.viewDidLoad()

    self.mainProfileTableView.contentInset = UIEdgeInsetsMake(-44,0,0,0);


    self.navigationController?.navigationBar.isOpaque = true
    UIApplication.shared.statusBarView?.backgroundColor = UIColor.init(red: 180/255, green: 40/255, blue: 56/255, alpha: 1.0)

    self.navigationController?.navigationBar.barTintColor = UIColor.init(red: 180/255, green: 40/255, blue: 56/255, alpha: 1.0)


    self.navigationController?.navigationBar.setBackgroundImage(UIImage(named : "navigationBarBackGround"), for: .default)

    self.navigationController?.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.isTranslucent = true
    self.navigationController?.view.backgroundColor = UIColor.init(red: 180/255, green: 40/255, blue: 56/255, alpha: 1.0)

}

这是检测用户向上或向下滚动的方法

var lastContentOffset: CGFloat = 0


func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if (self.lastContentOffset < scrollView.contentOffset.y) {
        // moved to top
        print("move Up\(scrollView.contentOffset.y)")
        print("alpha\(Float(scrollView.contentOffset.y / 166))")
        navigationController?.navigationBar.alpha = scrollView.contentOffset.y / 166

    } else if (self.lastContentOffset > scrollView.contentOffset.y) {
        // moved to bottom

        navigationController?.navigationBar.alpha = scrollView.contentOffset.y / 166
        print("alpha\(Float(scrollView.contentOffset.y / 166))")
        print("move down\(scrollView.contentOffset.y)")

    } else {

        // didn't move
    }
}

难道导航栏是半透明的? 像这样:

使用以下方式更改它:

self.navigationController?.navigationBar.isTranslucent = False

并删除:

self.navigationController?.navigationBar.setBackgroundImage...
self.navigationController?.navigationBar.shadowImage = UIImage()

然后在用户滚动时修改barTintColor

谢谢你的帮助但是我应该在滚动视图中使用半透明的 false Did Change Method 所以答案是这样

func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (self.lastContentOffset < scrollView.contentOffset.y) {
    // moved to top
    print("move Up\(scrollView.contentOffset.y)")
    print("alpha\(Float(scrollView.contentOffset.y / 166))")
    navigationController?.navigationBar.alpha = scrollView.contentOffset.y / 166
    if Float(scrollView.contentOffset.y / 166) >= 1.0 {

            self.navigationController?.navigationBar.isTranslucent = false

            }

} else if (self.lastContentOffset > scrollView.contentOffset.y) {
    // moved to bottom

    navigationController?.navigationBar.alpha = scrollView.contentOffset.y / 166
    print("alpha\(Float(scrollView.contentOffset.y / 166))")
    print("move down\(scrollView.contentOffset.y)")

} else {

    // didn't move
}
}