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

同以往的文章,这篇同样属于个人笔记,只为以后不重复造轮子,不为装逼。
自定义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,待续......

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,262评论 4 61
  • 百年孤独这部作品被堪称为经典。和大多数经典一样,每个人的理解都不同,有的人觉得平淡的故事,有的人觉得不愧为经典。 ...
    e8e976845a84阅读 261评论 5 2
  • 有一位法友,他问了一个问题:一位佛弟子,尤其是一位在家人,如何在生活当中,在工作、在家庭当中,修持佛法。今天下午就...
    石竹阅读 1,892评论 11 3
  • 感恩父母给予我生命养育我长大 感恩所有老师的教导 精进修行有了方向 感恩群里的小伙伴和仰心的支持与鼓励 感恩公司高...
    秀W阅读 238评论 0 0
  • 1、当Imageview上放btn的时候,需要开启Imageview的用户交互为Yes. 2、自己封装一个Cust...
    宝锤阅读 347评论 0 1