Published on

【Swift 初学系列】如何设置底部 TabBar(纯代码)🚀

Authors
  • avatar
    Name
    Tszkong Cheng
    Twitter

1. 准备工作 🛠️

本文基于【Swift 初学系列】新建项目(纯代码)🚀基础上开发,未初始化项目的可以先搭建好再浏览本篇文章

使用的设备和工具:

  • 一台 macOS 电脑 💻
  • Xcode 版本16.2 (建议使用最新版本)

Xcode Version

2. 创建 MainTabBarController ✨

  1. Common+N 选择 Cocoa Touch Class,点击 Next
    • Class:填 MainTabBarController
    • Subclass of:填 UITabBarController
    • 其他默认
  2. 点击 Next,选择保存路径并创建文件

image.png image.png

3. 修改入口

SceneDelegate.swift 文件的 scene 函数修改如下:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }
    window = UIWindow(windowScene: windowScene)
    window?.rootViewController = MainTabBarController()
    window?.makeKeyAndVisible()
}

4. 添加导航文件

  1. Common+N 选择 Cocoa Touch Class,点击 Next
    • Class:填 TodayViewController
    • Subclass of:填 UIViewController
    • 其他默认
  2. 点击 Next,选择保存路径并创建文件

重复1-3步骤分别创建:GameViewController AppViewController ArcadeViewController SearchViewController

image.png

4. 设置底部 TabBar 🏠

打开 MainTabBarController.swift 文件,添加如下代码:


import UIKit

class MainTabBarController: UITabBarController {

    override func viewLoad() {
        super.viewLoad()

        let todayVC = createTabBarItem(viewController: TodayViewController(), title: "Today", imageName: "doc.text.image")
        let gameVC = createTabBarItem(viewController: GameViewController(), title: "游戏", imageName: "paperplane")
        let appVC = createTabBarItem(viewController: AppViewController(), title: "App", imageName: "rectangle.on.rectangle")
        let arcadeVC = createTabBarItem(viewController: ArcadeViewController(), title: "Arcade", imageName: "gamecontroller")
        let searchVC = createTabBarItem(viewController: SearchViewController(), title: "搜索", imageName: "magnifyingglass")

        // 添加子控制器
        self.viewControllers = [todayVC, gameVC, appVC, arcadeVC, searchVC]

        tabBar.tintColor = .systemPink
        tabBar.barTintColor = .white
        tabBar.backgroundColor = .white
    }

    private func createTabBarItem(
        viewController: UIViewController,
        title: String,
        imageName: String
    ) -> UINavigationController {
        viewController.title = title
        viewController.tabBarItem = UITabBarItem(title: title, image: UIImage(systemName: imageName), selectedImage: UIImage(systemName: "\(imageName).fill"))

        let navController = UINavigationController(rootViewController: viewController)
        // 自定义 UINavigationBar 样式
        let appearance = UINavigationBarAppearance()
        appearance.backgroundColor = .white

        navController.navigationBar.standardAppearance = appearance
        navController.navigationBar.scrollEdgeAppearance = appearance // 滚动时外观

        return navController
    }
}

5. 运行项目 ▶️

点击 Xcode 界面左上角的运行按钮(或者使用快捷键 Cmd + R)🎯,模拟器将会启动

image.png

【Swift 初学系列】如何设置底部 TabBar(纯代码)🚀 | Chengtszkong's Blog