LoginSignup
24
27

More than 5 years have passed since last update.

SwiftでUITabBarとUINavigationBarをスクロール時にサクッと隠す

Last updated at Posted at 2016-09-23

homyuさんのUITabBarとUINavigationBarをスクロール時にサクッと隠すを参考にSwiftで書いたらどうなるかなーをやってみて、できたのでメモしておきます。

func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    if velocity.y > 0 {
        //上下のバーを隠す
        hidesBarsWithScrollView(scrollView, hidden: true, hiddenTop: true, hiddenBottom: true)
    } else {
        //上下のバーを表示する
        hidesBarsWithScrollView(scrollView, hidden: false, hiddenTop: true, hiddenBottom: true)
    }
}

/**
 * コントローラ上のtabBarとNavigationBarの表示/非表示を切り替える
 * @param scrollView 切り替え対象のScrollView
 * @param hidden     trueの場合は、下記パラメータに応じてバーを非表示にする
 * @param hiddenTop  trueの場合は、NavigationBarを非表示の対象にする
 * @param hiddenBottom  trueの場合は、Tabbarを非表示の対象にする
 **/
func hidesBarsWithScrollView(scrollView :UIScrollView,hidden:Bool,hiddenTop:Bool,hiddenBottom:Bool){
    let tabBarController = self.tabBarController
    var inset = scrollView.contentInset

    //上下バーのframe
    var tabBarRect = tabBarController?.tabBar.frame
    var topBarRect = self.navigationController?.navigationBar.frame

    //各パーツの高さ
    let tabBarHeight = tabBarController?.tabBar.frame.size.height
    let naviBarHeight = self.navigationController?.navigationBar.frame.size.height
    let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height
    let controllerHeight = tabBarController?.view.frame.size.height

    if hidden {
        if hiddenTop {
            topBarRect?.origin.y = -(naviBarHeight! + statusBarHeight)
            inset.top = 0
        }
        if hiddenBottom {
            tabBarRect?.origin.y = controllerHeight!
            inset.bottom = 0
        }
    } else {
        topBarRect?.origin.y = statusBarHeight
        inset.top = naviBarHeight! + statusBarHeight
        tabBarRect?.origin.y = controllerHeight! - tabBarHeight!
        inset.bottom = tabBarHeight!
    }

    UIView.animateWithDuration(0.5, animations: {() -> Void in
    scrollView.contentInset = inset
    scrollView.scrollIndicatorInsets = inset
    tabBarController?.tabBar.frame = tabBarRect!
    self.navigationController?.navigationBar.frame = topBarRect!
    })
}
24
27
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
27