我有一个桌面视图和一个导航栏。 我希望当用户向下滚动时,导航栏的背景颜色开始从清除变为红色,如增加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
}
}
答案 0 :(得分:1)
可以是导航栏半透明吗? 像这样:
使用以下方式更改:
self.navigationController?.navigationBar.isTranslucent = False
并删除:
self.navigationController?.navigationBar.setBackgroundImage...
self.navigationController?.navigationBar.shadowImage = UIImage()
然后在用户滚动时修改barTintColor
。
答案 1 :(得分: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
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
}
}