五种 自定义tabbar导航demo
自定义TabBar导航通常涉及到底部或顶部的一组按钮,用于在不同的视图控制器之间切换。以下是一个简单的自定义TabBar导航的实现示例:
import UIKit
class CustomTabBarController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupTabBar()
}
func setupTabBar() {
let firstViewController = UIViewController()
firstViewController.view.backgroundColor = .red
let secondViewController = UIViewController()
secondViewController.view.backgroundColor = .green
addChild(firstViewController)
addChild(secondViewController)
view.addSubview(firstViewController.view)
view.addSubview(secondViewController.view)
firstViewController.view.translatesAutoresizingMaskIntoConstraints = false
secondViewController.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
firstViewController.view.topAnchor.constraint(equalTo: view.topAnchor),
firstViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
firstViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
firstViewController.view.bottomAnchor.constraint(equalTo: view.centerYAnchor),
secondViewController.view.topAnchor.constraint(equalTo: view.centerYAnchor),
secondViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
secondViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
secondViewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
// 可以添加更多的视图控制器和相应的约束
}
}
// 在AppDelegate中设置window的rootViewController
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// 创建一个自定义的TabBarController
window?.rootViewController = CustomTabBarController()
window?.makeKeyAndVisible()
return true
}
这个示例展示了如何创建一个自定义的TabBarController,它有两个子视图控制器,每个视图控制器占据屏幕的一半。你可以根据需要添加更多的视图控制器和相应的TabBar按钮。这个例子使用了约束来布局子视图控制器的视图。
评论已关闭