UIWebView(WKWebViewではない!)を利用している画面で、スクロールに応じてナビゲーションバー/ツールバーを
表示/非表示にする機会があったのでメモ
##パターン1
hidesBarsOnSwipeをtrueにセットするだけでOK
ただし、私の環境(iOS11.3)において、UIWebViewでこれを利用してもアニメーションがおかしくなった...
override func viewDidLoad() {
self.navigationController?.setNavigationBarHidden(false, animated: true)
self.navigationController?.setToolbarHidden(false, animated: true)
self.navigationController?.hidesBarsOnSwipe = true
}
##パターン2
UIWebViewにUIScrollViewDelegateをセット
scroll位置を取得し、移動量に従ってsetToolbarHidden/setNavigationBarHiddenにtrue/falseを設定する
override func viewDidLoad() {
self.navigationController?.setNavigationBarHidden(false, animated: true)
self.navigationController?.setToolbarHidden(false, animated: true)
webview?.scrollView.delegate = self
}
extension MyViewController: UIScrollViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
scrollBeginPoint = scrollView.contentOffset
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
let scrollEndPoint = scrollView.contentOffset
if isBarShowing == true && scrollBeginPoint.y < scrollEndPoint.y {
self.navigationController?.setToolbarHidden(true, animated: true)
self.navigationController?.setNavigationBarHidden(true, animated: true)
isBarShowing = false
} else if isBarShowing == false && scrollBeginPoint.y > scrollEndPoint.y{
self.navigationController?.setToolbarHidden(false, animated: true)
self.navigationController?.setNavigationBarHidden(false, animated: true)
isBarShowing = true
}
}
}
##パターン3
scrollから値をとるのではなく、Gestureで判定したものから移動量に従ってsetToolbarHidden/setNavigationBarHiddenにtrue/falseを設定する
class MyViewController: UIViewController {
var isBarShowing = true
override func viewDidLoad() {
super.viewDidLoad()
let upSwipe = UISwipeGestureRecognizer(target: self, action: #selector(didUpSwipe(_:)))
upSwipe.direction = .up
upSwipe.delegate = self
let downSwipe = UISwipeGestureRecognizer(target: self, action: #selector(didDownSwipe(_:)))
downSwipe.direction = .down
downSwipe.delegate = self
self.view.addGestureRecognizer(upSwipe)
self.view.addGestureRecognizer(downSwipe)
}
@objc func didUpSwipe(_ sender: UITapGestureRecognizer) {
if isBarShowing {
self.navigationController?.setToolbarHidden(true, animated: true)
self.navigationController?.setNavigationBarHidden(true, animated: true)
isBarShowing = false
}
}
@objc func didDownSwipe(_ sender: UITapGestureRecognizer) {
if !isBarShowing {
self.navigationController?.setToolbarHidden(false, animated: true)
self.navigationController?.setNavigationBarHidden(false, animated: true)
isBarShowing = true
}
}