这是代码MCDTabBar
首先,您在扩展中创建一个委托。
//MARK: - Tab Bar Delegate
extension ViewController: MDCTabBarDelegate {
func tabBar(_ tabBar: MDCTabBar, didSelect item: UITabBarItem) {
guard let index = tabBar.items.firstIndex(of: item) else { return }
viewModel.selectedTabbarIndex = index
self.tableView.reloadData()
}
}
然后我们创建另一个扩展,其功能将设置标签栏:
//MARK: - Functions
extension ViewController {
func configureTabbar() {
tabbarView.clipsToBounds = false
tabbarView.backgroundColor = .clear
tabBar = MDCTabBar(frame: .zero)
tabBar.itemAppearance = .titles
tabBar.tintColor = .brightSkyBlue
tabBar.setTitleColor(.neutralDark, for: .selected)
tabBar.setTitleColor(.grey2, for: .normal)
tabBar.selectedItemTitleFont = Font.semibold.size(13)
tabBar.unselectedItemTitleFont = Font.semibold.size(13)
tabBar.backgroundColor = .clear
tabBar.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tabBar.clipsToBounds = false
tabBar.backgroundColor = .clear
tabBar.delegate = self
tabBar.sizeToFit()
self.tabbarView.addSubview(self.tabBar)
}
func configureTabBarCategories() {
for (index, categorie) in viewModel.categories.enumerated() {
let tabBarItem = UITabBarItem(title: categorie, image: nil, tag: index)
self.tabBar.items.append(tabBarItem)
}
}
}
而viewDidLoad
你只需调用函数。(另外,请检查我在下面分享的整个 ViewController 类。)
import UIKit
import MaterialComponents.MaterialTabs
class ViewController: UIViewController {
//MARK: - Outlets
@IBOutlet weak var tabbarView: UIView!
//MARK: - Properties
var viewModel: ViewModel!
var tabBar: MDCTabBar!
//MARK: - View Did Load
override func viewDidLoad() {
super.viewDidLoad()
configureTabbar()
configureTabBarCategories()
}
//MARK: - View Will Load
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tabBarController?.tabBar.isHidden = true
}
//MARK: - View Will Layout Subviews
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
tabBar.frame = CGRect(x: 0, y: 0, width: self.tabbarView.frame.width, height: self.tabbarView.frame.height)
}
}
许多扩展的目的是保持代码清晰和井井有条。
然后你应该在你的 ViewModel 中有这样的东西:
class SubscriptionsViewModel: BaseViewModel {
var categories: [String] = [
"First",
"Second",
"Third",
"Fourth"
]
//Sections
let FirstFilterIndex = 0
let SecondFilterIndex = 1
let ThirdFilterIndex = 2
let FourthFilterIndex = 3
func getSubscriptions() -> [Subscription] {
switch selectedTabbarIndex {
case FirstFilterIndex:
return someData1 //You decide what data to show.
case SecondFilterIndex:
return someData2 //You decide what data to show.
case ThirdFilterIndex:
return someData3 //You decide what data to show.
case FourthFilterIndex:
return someData4 //You decide what data to show.
default:
return []
}
}
}