iOS / Swift - 向下/向上滚动时隐藏/显示UITabBarController [英] iOS/Swift - Hide/Show UITabBarController when scrolling down/up

查看:233
本文介绍了iOS / Swift - 向下/向上滚动时隐藏/显示UITabBarController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对iOS开发很新。现在我正在尝试隐藏我的标签栏,当我向下滚动时,向上滚动标签栏应该出现。我想像导航栏一样动画这个动画。对于导航栏,我只需单击属性检查器中的选项。我看到了工具栏的一些示例,但我不能将其用作标签栏。

I'm quite new to iOS development. Right now i'm trying to hide my tabbar when I scroll down and when scrolling up the tabbar should appear. I would like to have this animated in the same way like the navigation bar. For the navigation bar I simply clicked the option in the Attributes Inspector. I saw some examples for the toolbar, but I cant adopt it the tabbar.

self.tabBarController?.tabBar.hidden = true 只是隐藏我的tabbar,但它不像导航控制器那样动画。

self.tabBarController?.tabBar.hidden = true just hides my tabbar, but its not animated like the navigation controller.

推荐答案

这是我实际在生产应用中使用的代码。

This is code that i'm actually using in a production app.

它在 Swift 中,它还会更新 UITabBar.hidden var。

It's in Swift and it also updates UITabBar.hidden var.

func scrollViewWillBeginDragging(scrollView: UIScrollView) {
    if scrollView.panGestureRecognizer.translation(in: scrollView).y < 0{
        changeTabBar(hidden: true, animated: true)
    }
    else{
        changeTabBar(hidden: false, animated: true)
    }
}

您还可以使用其他回调方法:

You can also use the other callback method:

func scrollViewDidScroll(scrollView: UIScrollView) {
    ...
}

但是如果你选择这样,那么你必须处理多个实际隐藏tabBar的辅助方法的调用。

but if you choose so, then you must handle multiple calls to the helper method that actually hides the tabBar.

然后你需要添加这个方法来激活tabBar的隐藏/显示。

And then you need to add this method that animates the hide/show of the tabBar.

func changeTabBar(hidden:Bool, animated: Bool){
    var tabBar = self.tabBarController?.tabBar
    if tabBar!.hidden == hidden{ return }
    let frame = tabBar?.frame
    let offset = (hidden ? (frame?.size.height)! : -(frame?.size.height)!)
    let duration:NSTimeInterval = (animated ? 0.5 : 0.0)
    tabBar?.hidden = false
    if frame != nil
    {
        UIView.animateWithDuration(duration,
            animations: {tabBar!.frame = CGRectOffset(frame!, 0, offset)},
            completion: {
                println($0)
                if $0 {tabBar?.hidden = hidden}
        })
    }
}

更新Swift 4

func changeTabBar(hidden:Bool, animated: Bool){
    guard let tabBar = self.tabBarController?.tabBar else { return; }
    if tabBar.isHidden == hidden{ return }
    let frame = tabBar.frame
    let offset = hidden ? frame.size.height : -frame.size.height
    let duration:TimeInterval = (animated ? 0.5 : 0.0)
    tabBar.isHidden = false

    UIView.animate(withDuration: duration, animations: {
        tabBar.frame = frame.offsetBy(dx: 0, dy: offset)
    }, completion: { (true) in
        tabBar.isHidden = hidden
    })
}

这篇关于iOS / Swift - 向下/向上滚动时隐藏/显示UITabBarController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆