这是一个很好的答案,但需要做一些调整才能正确实现。
基本思路是在scrollView中间放置一段文本,当用户向上滚动超过该文本时,该文本将成为新标题。此外,当您向下滚动时,它将更改回默认标题。
![enter image description here](https://istack.dev59.com/ge3Z7.webp)
![enter image description here](https://istack.dev59.com/EI4Im.webp)
所以,使用Gix发布的代码,现在已经转换为Swift 3,下面是如何完成它。
将这些变量添加到您的viewController的顶部
var didChangeTitle = false
let defaultTitle = "Default Title"
let animateUp: CATransition = {
let animation = CATransition()
animation.duration = 0.5
animation.type = kCATransitionPush
animation.subtype = kCATransitionFromTop
animation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseInEaseOut)
return animation
}()
let animateDown: CATransition = {
let animation = CATransition()
animation.duration = 0.5
animation.type = kCATransitionPush
animation.subtype = kCATransitionFromBottom
animation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseInEaseOut)
return animation
}()
在您的viewDidLoad中,添加以下代码来设置默认标题。
let titleLabelView = UILabel.init(frame: CGRect(x: 0, y: 0, width: 200, height: 44))
titleLabelView.backgroundColor = .clear
titleLabelView.textAlignment = .center
titleLabelView.textColor = UINavigationBar.appearance().tintColor
titleLabelView.font = UIFont.boldSystemFont(ofSize: 16)
titleLabelView.text = defaultTitle
self.navigationItem.titleView = titleLabelView
现在您需要在scrollView代理函数中添加一些代码:
extension MyViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y >= (labelName.frame.origin.y + labelName.frame.height) && !didChangeTitle {
if let label = navigationItem.titleView as? UILabel {
label.layer.add(animateUp, forKey: "changeTitle")
label.text = labelName.text
}
didChangeTitle = true
} else if scrollView.contentOffset.y < labelName.frame.origin.y && didChangeTitle {
if let label = navigationItem.titleView as? UILabel {
label.layer.add(animateDown, forKey: "changeTitle")
label.text = defaultTitle
}
didChangeTitle = false
}
}
}
“labelName”变量是滚动视图中包含您未来标题的标签。