原代码:
fileprivate func createSubiewControllers() { let newsVC = NewsViewController() let newsItem = UITabBarItem(title: "动态", image: UIImage(named: "TabNewsNormal"), selectedImage: UIImage(named: "TabNewsPressed")); newsVC.tabBarItem = newsItem let discoverVC = DiscoverViewController() let discoverItem = UITabBarItem(title: "发现", image: UIImage(named: "TabDiscoverNormal"), selectedImage: UIImage(named: "TabDiscoverPressed")); discoverVC.tabBarItem = discoverItem let nullVC = UIViewController() let nullItem = UITabBarItem() nullVC.tabBarItem = nullItem let messageVC = MessageViewController() let messageItem = UITabBarItem(title: "消息", image: UIImage(named: "TabMessageNormal"), selectedImage: UIImage(named: "TabMessagePressed")); messageVC.tabBarItem = messageItem let meVC = MeViewController() let meItem = UITabBarItem(title: "我", image: UIImage(named: "TabMeNormal"), selectedImage: UIImage(named: "TabMePressed")); meVC.tabBarItem = meItem self.viewControllers = [newsVC, discoverVC, nullVC, messageVC, meVC] let tabBarHeight = self.tabBar.frame.size.height let addButton = UIButton(type: .custom) if let addImage = UIImage(named: "TabAddButton") { addButton.frame = CGRect(x: 0, y: 0, width: addImage.size.width * (tabBarHeight - 12) / addImage.size.height, height: tabBarHeight - 12) addButton.setImage(addImage, for: .normal) } addButton.layer.masksToBounds = true addButton.layer.cornerRadius = 5 var center = self.tabBar.center center.y = self.tabBar.frame.size.height / 2 addButton.center = center self.tabBar.addSubview(addButton) }
效果:
没有显示第一个“动态”viewController。
原因:
self.viewControllers中要放UINavigationController所以将
self.viewControllers = [newsVC, discoverVC, nullVC, messageVC, meVC]
改为
let navNewsVC = UINavigationController(rootViewController: newsVC) let navDiscoverVC = UINavigationController(rootViewController: discoverVC) let navMessageVC = UINavigationController(rootViewController: messageVC) let navMeVC = UINavigationController(rootViewController: meVC) self.viewControllers = [navNewsVC, navDiscoverVC, nullVC, navMessageVC, navMeVC]
即可正确显示。