web-dev-qa-db-fra.com

UIAlertController change la couleur de la police

Voici mon code qui crée le 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)

Je ne vois pas comment changer la couleur du texte des actions annuler et appeler. Le texte du titre est actuellement noir et les boutons Annuler et Appeler sont blancs. Je m'efforce de les rendre tous noirs pour une meilleure visibilité. Des idées? Merci!

16
leerob

Après quelques essais et erreurs, j'ai trouvé que cela fonctionnait. J'espère que cela aidera les futurs nouveaux arrivants de Swift!

alertController.view.tintColor = UIColor.blackColor()
15
leerob

Le code ci-dessous modifie la couleur du titre 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 vous souhaitez changer la couleur du bouton, ajoutez le code suivant après le présent View Controller.

  alert.view.tintColor = UIColor.redColor()
5
Piyush Sanepara

Swift 4.2

Une façon de faire est de créer une extension sur UIAlertController, avec toutes les alertes de votre application ayant la même couleur. Mais cela laisse les actions destructrices dans la couleur rouge.

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

La réponse de Piyush m'a le plus aidé, mais voici quelques modifications pour Swift 3 et pour changer le titre et le message séparément.

Titre:

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

Message:

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

La grande taille de la police est due au fait que j’avais besoin de le faire pour tvOS, fonctionne très bien sur ce dernier et iOS.

3
CodyMace

Voici une mise à jour pour Swift 4, utilisant la réponse de Cody comme base:

Définition d'une couleur pour le titre de l'alerte:

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

Définition d'une couleur pour le message d'alerte:

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

Selon https://developer.Apple.com/documentation/foundation/nsattributedstring/key

0
podomunro

J'ai fait face au même problème et ai passé beaucoup de temps à essayer de trouver le meilleur moyen de changer sa couleur pour iOS 9 et iOS 10+ car elle est mise en œuvre de manière différente.

Enfin, j'ai créé une extension pour UIViewController. En extension, j'ai ajouté une fonction personnalisée qui est presque égale à la fonction par défaut "présent", mais effectue la correction des couleurs. Ici vous êtes ma solution. Applicable à Swift 3+, pour les projets avec cible à 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!()
            }
        })
    }
}

Pour utiliser cette fonction fixe, vous devez simplement appeler cette fonction au lieu de la fonction actuelle par défaut. Exemple:

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

Même solution, mais pour 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!()
            }
        }
    }
}

J'espère que cela aidera quelqu'un et permettra de gagner beaucoup de temps. Parce que mon temps n'a pas été économisé par une réponse aussi détaillée :)

0
DJ-Glock

Avant iOS 9.0, vous pouviez simplement changer la variable tintColor de la vue sous-jacente comme suit:

alertController.view.tintColor = UIColor.redColor()

Cependant, en raison d’un bogue introduit dans iOS 9, vous pouvez soit:

  1. Modifiez la teinteColor de l'application dans AppDelegate.

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
        self.window.tintColor = UIColor.redColor()
        return true
    }
    
  2. Réappliquez la couleur dans le bloc d'achèvement.

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

Voir mon autre réponse ici: https://stackoverflow.com/a/37737212/1781087

0
guidev