ios UITabBarItem 简单使用以及属性设置

100 阅读1分钟
//
//  MainController.swift
//  BookKeeping
//
//  Created by gy on 2022/12/6.
//

import Foundation
import UIKit


class MainController : UITabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initTabs()
    }
    
    private func initTabs(){
        let datas = TabEntity.createDatas()
        //直接设置 展示的图片有问题 默认是蓝色
//        datas.forEach { item in
//            item.page.tabBarItem = UITabBarItem().then({ attr in
//                attr.image = UIImage(named: item.icon)?.then({ img in
//                    print("img",img)
//                    img.withRenderingMode(.alwaysOriginal)
//                })
//                attr.selectedImage = UIImage(named: item.unSelectedIcon)?.then({ img in
//                    img.withRenderingMode(.alwaysOriginal)
//                })
//                attr.title = item.title
//            })
//        }
        self.tabBar.backgroundColor = .white
//        self.tabBar.tintColor = .clear
//        self.tabBar.barTintColor = .clear
//        self.tabBar.unselectedItemTintColor = .clear
        self.viewControllers = datas.map({ item in
            UINavigationController.init(rootViewController: item.page)
        })
        
        //解决ios 13 以上设置title 颜色不生效问题
        if #available(ios 13, *){
            self.tabBar.tintColor = .green
            self.tabBar.unselectedItemTintColor = .red
        }
        
        //这么设置就没有问题 展示的是原图
        // tabbar的imgage图片要按要求设置 2x 是30x30 不然展示会有问题
        for i in 0 ... (datas.count - 1) {
            self.tabBar.items?[i].then({ item in
                item.selectedImage = UIImage(named: datas[i].icon)?.withRenderingMode(.alwaysOriginal)
                item.image = UIImage(named: datas[i].unSelectedIcon)?.withRenderingMode(.alwaysOriginal)
                item.title = datas[i].title
                item.setTitleTextAttributes(
                    [NSAttributedString.Key.foregroundColor: UIColor.red,
                     NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18)],
                    for: .normal)
                item.setTitleTextAttributes(
                    [NSAttributedString.Key.foregroundColor: UIColor.green,
                     NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18)],
                    for: .selected)
            
            })
        }
       
    }
}