用户滚动时如何更改UINavigationBar barTintColor

时间:2016-03-23 16:55:34

标签: ios swift uinavigationbar

我想在用户滚动时将UINavigationBar.barTintColorUIColor.clearColor()更改为whiteColor(),但在用户滚动回到视图顶部时也会更改回清除状态。

这就是我一直在努力的;

viewDidLoad中

self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.backgroundColor = UIColor.clearColor()
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.barTintColor = UIColor.clearColor()

scrollViewDidScroll

override func scrollViewDidScroll(scrollView: UIScrollView) {
  self.navigationController?.navigationBar.shadowImage = UIImage()
  self.navigationController?.navigationBar.backgroundColor = UIColor.whiteColor()
  self.navigationController?.navigationBar.tintColor = UIColor.redColor()
  self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor()
}

然而,这不起作用,是否有人知道我如何能够完成我之后的效果?

1 个答案:

答案 0 :(得分:4)

最简单的解决方案:

func scrollViewDidScroll(scrollView: UIScrollView) {
        if (scrollView.contentOffset.y > 0) {
            self.navigationController?.navigationBar.backgroundColor = UIColor.whiteColor()
            self.navigationController?.navigationBar.tintColor = UIColor.redColor()
            self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor()
        } else {
            self.navigationController?.navigationBar.backgroundColor = UIColor.clearColor()
            self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
            self.navigationController?.navigationBar.barTintColor = UIColor.clearColor()
        }
    }