美文网首页Swift开发Swift开发技巧swift 文章收集
swift之自定义TabBar(目前个人认为最简单的方式)

swift之自定义TabBar(目前个人认为最简单的方式)

作者: 就怕是个demo | 来源:发表于2016-03-09 19:38 被阅读6235次

同以往的文章,这篇同样属于个人笔记,只为以后不重复造轮子,不为装逼。
自定义TabBar我知道的两种方式

  • 继承UITabBarController,在上次文章中《swift之自定义TabBarController》已经讲过
  • 自定义TabBar继承UIView,就是现在要讲的方式。

第一步:

屏幕快照 2016-03-09 15.38.17.png

在UIViewController上拖一个UIView作为5个tab的container,然后当然是拖五个UIButton放进container里面,将五个UIButton的上下左右约束都设置为零(这个按个人需求设),再选中5个UIButton设置等宽约束(够直白了吧。。。别介意这是对以后的我说的。)

第二步:(高潮来了)
注册UIButton对应的UIViewController

func layoutUI() {
    let _width = self.view.frame.width
    let _height = self.view.frame.height - 49
    
    self.homeVc = UIStoryboard.init(name: "Home", bundle: nil).instantiateViewControllerWithIdentifier("home_sid") as? NavigationController
    self.homeVc!.view.frame = CGRectMake(0, 0, _width, _height)
    //注册controller
    self.addChildViewController(self.homeVc!)
    
    self.discoverVc = UIStoryboard.init(name: "Discover", bundle: nil).instantiateViewControllerWithIdentifier("discover_sid") as? NavigationController
    self.discoverVc!.view.frame = CGRectMake(0, 0, _width, _height)
    self.addChildViewController(self.discoverVc!)
    
    self.messageVc = UIStoryboard.init(name: "Message", bundle: nil).instantiateViewControllerWithIdentifier("message_sid") as? NavigationController
    self.messageVc!.view.frame = CGRectMake(0, 0, _width, _height)
    self.addChildViewController(self.messageVc!)
    
    self.profileVc = UIStoryboard.init(name: "Profile", bundle: nil).instantiateViewControllerWithIdentifier("profile_sid") as? NavigationController
    self.profileVc?.view.frame = CGRectMake(0, 0, _width, _height)
    self.addChildViewController(self.profileVc!)

    self.view.addSubview(self.homeVc!.view)
}

override func viewDidLoad() {
    super.viewDidLoad()
    
    self._btnHome.selected = true
    layoutUI()
}

第三步:点击按钮切换controller
这里有两种方式

  • 这种方式请参考http://www.tuicool.com/articles/3ymMzub 写的够仔细了。但是这种方式用在本项目会有一瞬间的闪屏,所以采用第二种方式。
  • 本文采用的方式
func replaceController(newController: UIViewController) {
    //判断即将显示的controller是否已经压入栈
    if (newController.view.isDescendantOfView(self.view)) {
        //将该controller放到容器最上面显示出来
        self.view.bringSubviewToFront(newController.view);
    }
    else{
        self.view.addSubview(newController.view)
    }
}

结语:等项目做完放到github,待续......

相关文章

网友评论

本文标题:swift之自定义TabBar(目前个人认为最简单的方式)

本文链接:https://www.haomeiwen.com/subject/aettlttx.html