1. 程式人生 > >swift 真正移除下面的tabbar(最簡單的解決方式)

swift 真正移除下面的tabbar(最簡單的解決方式)

在使用push方式進行跳轉的時候,tabbar跟著顯示。有時候不需要它了,應該如何去掉呢

網上有很多種解決方案,原理大致相同(但是大部分方案只是做到了隱藏,隱藏後下面還是會有空白佔據一定的空間)如何把下面的空白也去掉呢?其實只需要三句程式碼或許兩句也能

方案一:(如果不行請看方案二)

我的解決方式.(有什麼不明白的可以在下面留言)

在需要隱藏tabbar的介面的ViewController中的viewWillAppear方法中新增兩行程式碼 (測試的時候第一句程式碼貌似不要也行)

          self.tabBarController?.hidesBottomBarWhenPushed

= true;

self.tabBarController?.tabBar.hidden = true//隱藏tabbar

self.automaticallyAdjustsScrollViewInsetsfalse//移除隱藏後留下的空白

這時候如果點選返回按鈕,關閉該介面會發現,根檢視的底部tabbar也被隱藏了,這當然不是我們想要的效果了

再根檢視控制器中再設定不讓它隱藏不就行了

self.tabBarController?.tabBar.hidden = false

2016.12.22更新

方案二:上面的程式碼之前執行完全可以達到效果。今天測試的竟然沒有用了,下面還是有黑色的佔據空間

後來發現是新新增的幾行程式碼讓上面這三行程式碼失效了。

具體原因是對tabbar的樣式進行設定的程式碼讓這三行程式碼失效了,屌不屌,坑不坑。(tabbar樣式設定請參考:http://blog.csdn.net/wei_chong_chong/article/details/53763662)

但是我又發現了更加簡單的方式

在需要隱藏底部tabbar的介面的stroyboard中設定一下就ok了


  下面是網上其它的解決方式,但是他們只是隱藏了tabbar沒有移除空白,我是在他們的基礎上改進的。

控制器有個hidesBottomBarWhenPushed屬性。官方的定義是:// If YES, then when this view controller is pushed into a controller hierarchy with a bottom bar (like a tab bar), the bottom bar will slide out. Default is NO. 即,當控制器被push進一個控制器之後,底部條(比如tabBar)會滑出。預設為NO。

現在假設一種情況,tabBarController上放著四個導航控制器,那麼要想實現push進一個新的控制器的時候,將tabBarController的tabBar隱藏,只要設定hidesBottomBarWhenPushed = YES;那如果想要隱藏呢?有的人可能會這麼做:在viewWillApper裡面加入下面的程式碼:

if (self.navigationController?.viewControllers.count == 1) {

self.tabBarController.tabBar.hidden = false;

}

這樣做,在第一遍返回到tabBarController上時,是沒問題的。但是當第二次再push進入一個新的控制器時,你會發現,hidesBottomBarWhenPushed根本沒生效,怎麼解決呢?

將viewWillAppear裡面的程式碼更換成:

if (self.navigationController?.viewControllers.count > 1) {

self.tabBarController?.tabBar.hidden = true;

        }else {

self.tabBarController?.tabBar.hidden = false;

        }

這時就完美的解決了問題。

這個時候,也有人可能會問:是不是隻要在viewWillAppear裡面加入那些程式碼就可以,不用設定hidesBottomBarWhenPushed屬性為YES。那麼你只要試一下,你就會知道。。

網上方式2.

 func setTabBarVisible(visible:Bool, animated:Bool) {
          if (tabBarIsVisible() == visible) { return }
        
        let frame = self.tabBarController?.tabBar.frame
        let offsetY:CGFloat = (visible ? 49.0 : 49.0)
        
        let duration:NSTimeInterval = (animated ? 0.3 : 0.0)
        if frame != nil {
            UIView.animateWithDuration(duration) {
                self.tabBarController?.tabBar.frame = CGRectOffset(frame!, 0, offsetY)
                return
            }
        }
    }
    
    func tabBarIsVisible() ->Bool {
        return self.tabBarController?.tabBar.frame.origin.y < CGRectGetMaxY(self.view.frame)
    }

然後呼叫

setTabBarVisible(true, animated: false)

參考:

http://www.cnblogs.com/ritian/p/5248451.html