uialert objective example swift ios8 uialertcontroller

objective - uialertcontroller swift 4 example



UIAlertController cambiar el color de la fuente (7)

Aquí está mi código que crea el UIAlertController

// Create the alert controller var alertController = UIAlertController(title: "Are you sure you want to call /(self.number)?", message: "", preferredStyle: .Alert) // Create the actions var okAction = UIAlertAction(title: "Call", style: UIAlertActionStyle.Default) { UIAlertAction in var url:NSURL = NSURL(string: "tel:///(self.number)")! UIApplication.sharedApplication().openURL(url) } var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { UIAlertAction in } // Add the actions alertController.addAction(okAction) alertController.addAction(cancelAction) // Present the controller self.presentViewController(alertController, animated: true, completion: nil)

No puedo averiguar cómo cambiar el color del texto de las acciones de cancelar y llamar. El texto del título está actualmente en negro y los botones de cancelar y llamar están en blanco. Estoy haciendo que todos sean negros para una mejor visibilidad. ¿Algunas ideas? ¡Gracias!


Antes de iOS 9.0, simplemente puedes cambiar el tintColor la vista subyacente de esta manera:

alertController.view.tintColor = UIColor.redColor()

Sin embargo, debido a un error introducido en iOS 9, puede:

  1. Cambia la aplicación tintColor en el AppDelegate.

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { self.window.tintColor = UIColor.redColor() return true }

  2. Vuelva a aplicar el color en el bloque de finalización.

    self.presentViewController(alert, animated: true, completion: {() -> Void in alert.tintColor = UIColor.redColor() })

Vea mi otra respuesta aquí: https://.com/a/37737212/1781087


Aquí hay una actualización para Swift 4, utilizando la respuesta de Cody como base:

Configuración de un color para el título de alerta:

alert.setValue(NSAttributedString(string: alert.title!, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.medium), NSAttributedStringKey.foregroundColor : UIColor.blue]), forKey: "attributedTitle")

Configurar un color para el mensaje de alerta:

alert.setValue(NSAttributedString(string: alert.message, attributes: [NSAttributedStringKey : UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.Medium), NSAttributedStringKey.foregroundColor : UIColor.green]), forKey: "attributedMessage")

Según https://developer.apple.com/documentation/foundation/nsattributedstring/key


Debajo del código está cambiando el color del título de UIAlertView .

let alert = UIAlertController(title: messageTitle, message: messageText, preferredStyle: UIAlertControllerStyle.Alert) alert.setValue(NSAttributedString(string: messageTitle, attributes: [NSFontAttributeName : UIFont.systemFontOfSize(17),NSForegroundColorAttributeName : UIColor.redColor()]), forKey: "attributedTitle") alert.addAction(UIAlertAction(title: buttonText, style: UIAlertActionStyle.Default, handler: nil)) parent.presentViewController(alert, animated: true, completion: nil)

Si desea cambiar el color del botón, agregue el siguiente código después del presente View Controller.

alert.view.tintColor = UIColor.redColor()


Después de algunas pruebas y errores, encontré que esto funcionó. ¡Espero que esto ayude a futuros recién llegados!

alertController.view.tintColor = UIColor.blackColor()


He enfrentado el mismo problema y he pasado mucho tiempo tratando de encontrar la mejor manera de cambiar su color para iOS 9 y iOS 10 + porque se implementa de una manera diferente.

Finalmente he hecho una extensión para UIViewController. En la extensión, he agregado una función personalizada que es casi igual a la función predeterminada "presente", pero realiza una corrección de colores. Aquí tienes mi solución. Aplicable para swift 3+, para proyectos con destino a partir de iOS 9:

extension UIViewController { /// Function for presenting AlertViewController with fixed colors for iOS 9 func presentAlert(alert: UIAlertController, animated flag: Bool, completion: (() -> Swift.Void)? = nil){ // Temporary change global colors UIView.appearance().tintColor = UIColor.red // Set here whatever color you want for text UIApplication.shared.keyWindow?.tintColor = UIColor.red // Set here whatever color you want for text //Present the controller self.present(alert, animated: flag, completion: { // Rollback change global colors UIView.appearance().tintColor = UIColor.black // Set here your default color for your application. UIApplication.shared.keyWindow?.tintColor = UIColor.black // Set here your default color for your application. if completion != nil { completion!() } }) } }

Para usar esta función fija, debe llamar a esta función en lugar de la función presente predeterminada. Ejemplo:

self.presentAlert(alert: alert, animated: true)

La misma solución, pero para UIActivityViewController:

extension UIViewController { /// Function for presenting UIActivityViewController with fixed colors for iOS 9 and 10+ func presentActivityVC(vc: UIActivityViewController, animated flag: Bool, completion: (() -> Swift.Void)? = nil) { // Temporary change global colors for changing "Cancel" button color for iOS 9 and 10+ if UIDevice.current.systemVersion.range(of: "9.") != nil { UIApplication.shared.keyWindow?.tintColor = ColorThemes.alertViewButtonTextColor } else { UILabel.appearance().textColor = ColorThemes.alertViewButtonTextColor } self.present(vc, animated: flag) { // Rollback for changing global colors for changing "Cancel" button color for iOS 9 and 10+ if UIDevice.current.systemVersion.range(of: "9.") != nil { UIApplication.shared.keyWindow?.tintColor = ColorThemes.tintColor } else { UILabel.appearance().textColor = ColorThemes.textColorNormal } if completion != nil { completion!() } } } }

Espero que esto ayude a alguien y ahorre mucho tiempo. Porque mi tiempo no fue ahorrado por una respuesta tan detallada :)


La respuesta de Piyush fue la que más me ayudó, pero aquí hay algunos ajustes para Swift 3 y para cambiar el título y el mensaje por separado.

Título:

alert.setValue(NSAttributedString(string: alert.message, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 29, weight: UIFontWeightMedium), NSForegroundColorAttributeName : UIColor.red]), forKey: "attributedTitle")

Mensaje:

alert.setValue(NSAttributedString(string: alert.message, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 29, weight: UIFontWeightMedium), NSForegroundColorAttributeName : UIColor.red]), forKey: "attributedMessage")

El gran tamaño de fuente se debe a que en realidad necesitaba hacerlo para tvOS, funciona muy bien en él y en iOS.


Swift 4.2

Una forma de hacerlo es hacer una extensión en UIAlertController, con esto todas las alertas de su aplicación tienen el mismo color de tinte. Pero deja acciones destructivas en color rojo.

extension UIAlertController{ open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.view.tintColor = .yourcolor } }