UITabBarController支持用户在一组不同的屏幕之间切换,通常作为整个程序的root controller,例如微信的页面就是。
这里就用微信的样式作为示例。
- WeChatViewController
- ContactViewController
- FindViewController
- MineViewController
class WeChatViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.red
let label = UILabel(frame: CGRect(x: 0, y: 200, width: UIScreen.main.bounds.width, height: 50))
label.backgroundColor = UIColor.white
label.font = UIFont.systemFont(ofSize: 15)
label.textColor = UIColor.gray
label.textAlignment = NSTextAlignment.center
label.text = "微信"
view.addSubview(label)
}
}
在AppDelegate中的didFinishLaunchingWithOptions创建UITabBarController,并且设置其viewControllers属性。
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let wechat = WeChatViewController()
// 未选中状态Tab图片
wechat.tabBarItem.image = UIImage(named: "tab1")?.withRenderingMode(.alwaysOriginal)
// 选中状态Tab图片
wechat.tabBarItem.selectedImage = UIImage(named: "selectTab1")?.withRenderingMode(.alwaysOriginal)
// Tab的文本
wechat.tabBarItem.title = "微信"
// 未读消息角标
wechat.tabBarItem.badgeValue = "10"
let addressBook = ContactViewController()
addressBook.tabBarItem.image = UIImage(named: "tab2")?.withRenderingMode(.alwaysOriginal)
addressBook.tabBarItem.selectedImage = UIImage(named: "selectTab2")?.withRenderingMode(.alwaysOriginal)
addressBook.tabBarItem.title = "通讯录"
let find = FindViewController()
find.tabBarItem.image = UIImage(named: "tab3")?.withRenderingMode(.alwaysOriginal)
find.tabBarItem.selectedImage = UIImage(named: "selectTab3")?.withRenderingMode(.alwaysOriginal)
find.tabBarItem.title = "发现"
let mine = MineViewController()
mine.tabBarItem.image = UIImage(named: "tab4")?.withRenderingMode(.alwaysOriginal)
find.tabBarItem.selectedImage = UIImage(named: "selectTab4")?.withRenderingMode(.alwaysOriginal)
mine.tabBarItem.title = "我的"
let tabBarController = UITabBarController()
// tabBarController的主题颜色
tabBarController.tabBar.tintColor = UIColor.white
// 修改tabBar位置
// tabBarController.tabBar.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44)
// tabBarController的子视图控制器集合
tabBarController.viewControllers = [wechat,addressBook,find,mine]
tabBarController.selectedIndex = 2
// 添加到rootViewController
window?.rootViewController = tabBarController
return true
}
}
- 邮箱 :charon.chui@gmail.com
- Good Luck!