本帖最后由 莫问刀 于 2021-3-9 16:37 编辑
默认掘金的底部tab学习笔记
背景
做一个类似掘金底部的tabbar,多个tab切换
UITabBarController使用
//
// MainViewController.swift
// uitable
//
// Created by Alice on 2021/3/8.
//
import UIKit
class MainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
initTab()
}
func initTab() {
let homeVC = WxListController()
homeVC.tabBarItem.title = "首页"
homeVC.tabBarItem.image = UIImage(named: "tab_home_normal")
let activityVC = ActivityViewController()
activityVC.tabBarItem.title = "沸点"
activityVC.tabBarItem.image = UIImage(named: "tab_activity")
let findVC = FindViewController()
findVC.tabBarItem.title = "发现"
findVC.tabBarItem.image = UIImage(named: "tab_find_normal")
let ceVC = CeViewController()
ceVC.tabBarItem.title = "小册"
ceVC.tabBarItem.image = UIImage(named: "tab_xiaoce_normal")
let meVC = MeViewController()
meVC.tabBarItem.title = "我的"
meVC.tabBarItem.image = UIImage(named: "tab_profile_normal")
//设置多个控制器到这个属性中
viewControllers = [homeVC, activityVC, findVC, ceVC, meVC]
//设置图标的着色和默认颜色,都是从掘金吸出来的。图片资源也是解压出来的。
setTabBarItemAttributes(fontName: "Courier", fontSize: 13, normalColor: ColorUtils.parser("#969695")!, selectedColor: ColorUtils.parser("#027AFF")!, bgColor: UIColor.white)
}
func setTabBarItemAttributes(fontName: String = "Courier",
fontSize: CGFloat = 14,
normalColor: UIColor = .gray,
selectedColor: UIColor = .red,
bgColor: UIColor = .white) {
// tabBarItem 文字大小
var attributes: [NSAttributedString.Key: Any] = [.font: UIFont(name: fontName, size: fontSize)!]
// tabBarItem 文字默认颜色
attributes[.foregroundColor] = normalColor
UITabBarItem.appearance().setTitleTextAttributes(attributes, for: .normal)
// tabBarItem 文字选中颜色
attributes[.foregroundColor] = selectedColor
UITabBarItem.appearance().setTitleTextAttributes(attributes, for: .selected)
// tabBar 文字、图片 统一选中高亮色
tabBar.tintColor = selectedColor
// tabBar 背景色
tabBar.barTintColor = bgColor
}
}
修改app的启动入口
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//创建默认window
window = UIWindow.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
window?.backgroundColor = .white
window?.rootViewController = MainViewController()
//设置导航器
//设置nav作为主窗口
//显示主窗口(默认不显示)
window?.makeKeyAndVisible()
return true
}
创建其他几个tab
其中一个:
//
// MeViewController.swift
// uitable
//
// Created by Alice on 2021/3/8.
//
import UIKit
import SnapKit
class MeViewController: UIViewController {
private lazy var lab: UILabel = {
let label = UILabel()
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(lab)
lab.text = "me"
lab.snp.makeConstraints { (make) in
make.center.equalToSuperview()
}
}
}
整个基础的tab实现就完成了。
接下来就是在页面中展示内容,和页面跳转了。
代码地址:
https://github.com/cat13954/IOSUiTableViewSample
如果对你有帮助,记得GitHub star哦
|