。
注:根據您的用戶界面和中心tabBarItem
圖像默認顏色爲白色
class tabbarVCViewController: UITabBarController, UITabBarControllerDelegate {
// MARK: - ViewController Override Methods.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupInitilView()
}
// MARK: - setup Initial View Methode.
private func setupInitilView() {
delegate = self
// Sets the default color of the icon of the selected UITabBarItem and Title
UITabBar.appearance().tintColor = UIColor.white
// Sets the default color of the background of the UITabBar
UITabBar.appearance().barTintColor = UIColor.white
// Sets the background color of the selected UITabBarItem (using and plain colored UIImage with the width = 1/5 of the tabBar (if you have 5 items) and the height of the tabBar)
//UITabBar.appearance().selectionIndicatorImage = UIImage().makeImageWithColorAndSize(color: UIColor.black, size: CGSize.init(width: tabBar.frame.width/4, height: tabBar.frame.height))
// Uses the original colors for your images, so they aren't not rendered as grey automatically.
for item in self.tabBar.items! {
if let image = item.image {
//item.image = image.withRenderingMode(.alwaysTemplate)
item.image = image.withRenderingMode(.alwaysOriginal) //Use default image colour as grey colour and your centre image default colour as white colour as your requirement.
}
}
//Change the backgound colour of specific tabBarItem.
let itemIndex:CGFloat = 2.0
let bgColor = UIColor.black
let itemWidth = tabBar.frame.width/CGFloat(tabBar.items!.count)
let bgView = UIView(frame: CGRect.init(x: itemWidth * itemIndex, y: 0, width: itemWidth, height: tabBar.frame.height))
bgView.backgroundColor = bgColor
tabBar.insertSubview(bgView, at: 0)
}
// MARK: - UITabbarController Override Methods .
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
}
// MARK: - UITabBarControllerDelegate Methods
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
return true
}
}
使用tabBarItem
圖像默認顏色爲灰色:下面所有的代碼在一個延伸的UITabBarController作爲一個自定義類使用資產中。
你將要擴展的UIImage類,以與大小素色圖像,你需要:
extension UIImage {
func makeImageWithColorAndSize(color: UIColor, size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(CGRect.init(x: 0, y: 0, width: size.width, height: size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
謝謝你..我已經通過這個答案在這裏:https:// stacko verflow.com/a/26753432/4033273 –
還有其他更好的選擇嗎? –