我是否可以建议一种更简单的方法,从 Storyboard 设置标签栏控制器往往会随着应用程序大小的增长而变得非常复杂且难以维护。相反,从 appdelegate 创建它并修改 didFinishLaunchingWithOptions 方法会容易得多。在此解决方案中,我显示了两个选项卡。我演示了如何从 Storyboard 设置一个选项卡,从一个视图控制器设置另一个选项卡,您可以在其中以编程方式设置内容。我还展示了如何自定义标签栏,以及如何自定义实现标签栏控制器时出现的导航栏。
//this will hold the root
var rootController: UIViewController!
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//modify didFinishLaunchingWithOptions in your app delegate as follows
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let tabController = UITabBarController()
//setup a view controller from another storyboard
let workoutsStoryboard = UIStoryboard(name: "Workouts", bundle: nil)
//this tab will start from a storyboard of its own
let homeVC = workoutsStoryboard.instantiateViewController(withIdentifier: "home") as! HomeViewController
//this will setup another tab bar but from a view controller only if you want to setup things programmatically
let profileVC = ProfileViewController()
//setup the tab bar elements with the icons, name and initial view controllers
let vcData: [(UIViewController, UIImage, String)] = [
(homeVC, UIImage(named: "home_tabbar_icon")!, "Home"),
(profileVC, UIImage(named: "feed_tabbar_icon")!, "Profile")
]
let vcs = vcData.map { (vc, image, title) -> UINavigationController in
let nav = UINavigationController(rootViewController: vc)
nav.tabBarItem.image = image
nav.title = title
return nav
}
//customize your tab bar
tabController.viewControllers = vcs
tabController.tabBar.barTintColor = UIColor(hexString: "#FAFAFA")
tabController.tabBar.tintColor = UIColor(hexString: "#4A4A4A")
tabController.tabBar.isTranslucent = false
if let items = tabController.tabBar.items {
for item in items {
if let image = item.image {
item.image = image.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
}
}
}
//make your tab bar the root
window?.rootViewController = tabController
//tab bar comes with a nav bar. here is how to customize it
UIApplication.shared.statusBarStyle = .lightContent
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
UINavigationBar.appearance().isTranslucent = false
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().backgroundColor = UIColor.white
UINavigationBar.appearance().barTintColor = UIColor(hexString: "#4A90E2")
rootController = (window?.rootViewController)!
return true
}
如果您想知道如何在上面的示例中从主页设置故事板,您需要做的就是转到新建->文件并选择故事板。将故事板称为“Home”,当它进入您的项目时,选择它并在文件检查器中将其名称更改为“Home.storyboard”。
现在您可以转到该情节提要并添加您想要的导航控制器作为初始视图控制器以及跟随它的所有其他视图控制器。
我鼓励为每个标签设置一个故事板。它使事物保持清洁和分离。或者您可以通过编程方式完成,而无需添加情节提要,而只需从视图控制器文件中进行设置。都是一样的。