ios swift ios8 uitabbar uitabbaritem

Color de fondo del elemento de la barra de pestañas de IOS 8



swift ios8 (5)

He estado tratando de encontrar la solución a esto durante la última semana, y no he tenido suerte después de probar todas las soluciones posibles que pude encontrar o pensar. Todas las soluciones que encontré y he intentado no han funcionado o han quedado desactualizadas.

Tengo 5 UITabBarItem ''s en una UITabBar ubicada dentro de UITabBarController . Quiero cambiar el color de fondo del UITabBarItem cuando está seleccionado y, por supuesto, hacer que vuelva a cambiar cuando cambie el elemento seleccionado.

Estoy usando Swift y iOS SDK 8.3 en Xcode 6.3.1. Si solo puedes responder en Objective-C que también está bien, ¡cualquier respuesta te ayudará! Gracias a todos de antemano, realmente lo aprecio!

EDITAR: Aquí hay un ejemplo visual de lo que me gustaría que hiciera.

Color de fondo diferente


¿Has probado esto?

Seleccione la imagen del icono de la barra de pestañas en su controlador de vista en el guión gráfico.

Mire en la pestaña Identidad y Tipo (extremo izquierdo) (parece un trozo de papel) en el panel derecho de xcode.

Busque la configuración de tinte global.


En tu tabBarController, puedes establecer la UITabBar tintColor, barTintColor, selectionIndicatorImage predeterminada (hacer un poco de trampa aquí) y el modo de reproducción de las imágenes, consulta los comentarios a continuación:

class MyTabBarController: UITabBarController, UINavigationControllerDelegate { ... override func viewDidLoad() { ... // Sets the default color of the icon of the selected UITabBarItem and Title UITabBar.appearance().tintColor = UIColor.redColor() // Sets the default color of the background of the UITabBar UITabBar.appearance().barTintColor = UIColor.blackColor() // 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(UIColor.blueColor(), size: CGSizeMake(tabBar.frame.width/5, 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 as! [UITabBarItem] { if let image = item.image { item.image = image.imageWithRenderingMode(.AlwaysOriginal) } } } ... }

Y querrá extender la clase UIImage para hacer la imagen de color liso con el tamaño que necesita:

extension UIImage { func makeImageWithColorAndSize(color: UIColor, size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0) color.setFill() UIRectFill(CGRectMake(0, 0, size.width, size.height)) var image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }


Inspirado por Gwendle, así lo he resuelto:

override func viewWillAppear(animated: Bool) { guard let tabBar = tabBarController?.tabBar else { return } tabBar.tintColor = UIColor.whiteColor() tabBar.selectionIndicatorImage = UIImage().makeImageWithColorAndSize(UIColor.redColor(), size: CGSizeMake(tabBar.frame.width/5, tabBar.frame.height)) super.viewWillAppear(animated) }

Y también usé la extensión:

extension UIImage { func makeImageWithColorAndSize(color: UIColor, size: CGSize) -> UIImage { UIGraphicsBeginImageContext(size) color.setFill() UIRectFill(CGRectMake(0, 0, size.width, size.height)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image }

Tenga en cuenta que después de establecer la selectionIndicationImage , permanecerá configurado para todas las demás pestañas. Aquí hay un ejemplo de cómo eliminarlo, configurándolo en cero en todos los demás controladores de vista en las pestañas restantes:

override func viewWillAppear(animated: Bool) { tabBarController?.tabBar.tintColor = UIColor.redColor() tabBarController?.tabBar.selectionIndicatorImage = nil super.viewWillAppear(animated) }

Implementado utilizando Swift 2.


Puede llamar a esta función desde cada controlador pasando self.tabBarController y cada color que desee.

Función:

static func customTabBar(controller: UIViewController?, backgroundColor: String, unselectedColor: String, selectedColor: String) { if let tabBarController = controller as? UITabBarController { tabBarController.tabBar.barTintColor = UIColor(hex: backgroundColor) tabBarController.tabBar.tintColor = UIColor(hex: selectedColor) tabBarController.tabBar.isTranslucent = false tabBarController.tabBar.selectedItem?.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor(hex: selectedColor)], for: UIControl.State.selected) if #available(iOS 10.0, *) { tabBarController.tabBar.unselectedItemTintColor = UIColor(hex: unselectedColor) } else { // Fallback on earlier versions } } }


Puedes probar este. Añade esto en AppDelegate.swift .

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. UITabBar.appearance().translucent = false UITabBar.appearance().barTintColor = UIColor(rgba: "#12296f") UITabBar.appearance().tintColor = UIColor.whiteColor() return true }

No olvides incluir esta biblioteca. https://github.com/yeahdongcn/UIColor-Hex-Swift