Подтвердить что ты не робот

Изменение цвета шрифта UIAlertController

Здесь мой код, который создает 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)

Я не могу понять, как изменить цвет текста действий отмены и вызова. Текст заголовка в настоящее время черный, а кнопки отмены и вызова белые. Я делаю, чтобы сделать их черными для лучшей видимости. Есть идеи? Спасибо!

4b9b3361

Ответ 1

После некоторых проб и ошибок, я нашел, что это сработало. Надеюсь, это поможет будущим быстрым новичкам!

alertController.view.tintColor = UIColor.blackColor()

Ответ 2

Ниже код изменяет цвет заголовка 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)

Если вы хотите изменить цвет кнопки, добавьте следующий код после текущего View Controller.

  alert.view.tintColor = UIColor.redColor()

Ответ 3

Swift 4.2

Один из способов сделать это - создать расширение на UIAlertController, при этом все предупреждения вашего приложения будут иметь одинаковый оттенок. Но это оставляет разрушительные действия в красном цвете.

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

Ответ 4

Ответ Piyush помог мне больше всего, но вот некоторые настройки для Swift 3 и изменение названия и сообщения отдельно.

Название:

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

Сообщение:

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

Большой размер шрифта - это то, что мне действительно нужно сделать это для tvOS, отлично работает на нем и iOS.

Ответ 5

Вот обновление для Swift 4, использующее ответ Коди в качестве основы:

Установка цвета для заголовка предупреждения:

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

Установка цвета для предупреждающего сообщения:

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

Согласно https://developer.apple.com/documentation/foundation/nsattributedstring/key

Ответ 6

Перед iOS 9.0 вы можете просто изменить основной вид tintColor следующим образом:

alertController.view.tintColor = UIColor.redColor()

Однако из-за ошибки, введенной в iOS 9, вы можете:

  • Измените приложение tintColor в AppDelegate.

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
        self.window.tintColor = UIColor.redColor()
        return true
    }
    
  • Повторите цвет в блоке завершения.

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

См. мой другой ответ здесь: fooobar.com/questions/496916/...

Ответ 7

Я столкнулся с той же проблемой и потратил много времени, пытаясь найти лучший способ изменить его цвет для iOS 9 и iOS 10+, потому что он реализован по-другому.

Наконец, я сделал расширение для UIViewController. В добавлении я добавил пользовательскую функцию, которая почти равна функции по умолчанию "present", но выполняет исправление цветов. Вот ты мое решение. Применимо для быстрых 3+ для проектов с целевыми значениями, начиная с 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!()
            }
        })
    }
}

Чтобы использовать эту фиксированную функцию, вы должны просто вызвать эту функцию вместо текущей функции по умолчанию. Пример:

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

То же решение, но для 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!()
            }
        }
    }
}

Надеюсь, это поможет кому-то и сэкономит много времени. Поскольку мое время не было сохранено таким подробным ответом:)