Цвет оттенка UIAlertController по умолчанию - синий.
Я использую следующий код, чтобы представить лист действий UIAlertController с текстом элемента как красным. Я использовал свойство tint для установки цвета.
UIAlertController *alertController = [UIAlertController
alertControllerWithTitle:nil
message:nil
preferredStyle:UIAlertControllerStyleActionSheet];
alertController.view.tintColor = [UIColor redColor];
Цвет текста, по-видимому, по умолчанию не совпадает с синим цветом по выделенному или выделенному значению. Это нормально и как это остановить?
Ответы
Ответ 1
Это известная ошибка, см. https://openradar.appspot.com/22209332
Чтобы исправить это, повторно примените цвет оттенка в обработчике завершения. Здесь мое быстрое решение, вы сможете легко адаптировать его для ObjC:
alertController.view.tintColor = UIColor.redColor() // apply 1st time to prevent flicker from Blue to Red when displaying
navigationController?.presentViewController(alertController, animated: true, completion: {
// Bugfix: iOS9 - Tint not fully Applied without Reapplying
alertController.view.tintColor = UIColor.redColor()
})
Одно примечание: это не исправляет ошибку полностью. При повороте устройства вы заметите, что кнопки перекрашены с оттенком System Default (= Blue).
Ожидайте, что он будет исправлен с помощью iOS 9.1.
Редактировать 10/23/2015: Все еще не исправлено с iOS 9.1. Обновлен с iOS 9.1 + Xcode 7.1 (7B91B), выпущенный пару дней назад. На данный момент установка .tintColor не работает, однако, как указано в комментариях, вы можете установить tintColor для всего Приложения, например. в приложении AppDelegate didFinishLaunchingWithOptions установлено window?.tintColor = UIColor.redColor()
. Это также уменьшает кнопки AlertController, но может быть неприемлемо в некоторых случаях, поскольку этот оттенок применяется во всем приложении.
Ответ 2
Просто добавьте tintColor после текущегоViewController. Работает на iOS 9.0.2
[self presentViewController:alertController animated:YES completion:nil];
[alertController.view setTintColor:[UIColor yellowColor]];
Ответ 3
Вы также можете изменить цвет оттенка приложения в appdelegate.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window.tintcolor = [UIColor yellowColor];
return YES;
}
отлично подходит для меня.
Ответ 4
Вы можете изменить цвет кнопки следующим образом
UIAlertAction* button = [UIAlertAction
actionWithTitle:@"Delete Profile"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
//Add Action.
}];
[button setValue:[UIColor redColor] forKey:@"titleTextColor"];
Используя эту строку [button setValue: [UIColor redColor] дляKey: @ "titleTextColor" ];
Вы можете изменить цвет кнопки вашего листа действий.
Ответ 5
Установите цвет оттенка в traitCollectionDidChange
в подклассе UIAlertController
.
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
self.view.tintColor = UIColor.redColor()
}
Ответ 6
Просто измените свой вид tintAdjustmentMode на UIViewTintAdjustmentModeNormal, поэтому он не изменит его цвет на dimm.
Ответ 7
Я все еще смущен тем, чего вы хотите достичь. Но вы можете попробовать Apple создать кнопки Destructive
(по умолчанию цвет текста красный).
Код, в котором вы создаете UIAlertAction
, не использует стиль Default
для кнопок, которые вы хотите в красном цвете. Вместо этого используйте UIAlertActionStyleDestructive
. Пример кода:
UIAlertAction* cancel = [UIAlertAction
actionWithTitle:@"Cancel"
style:UIAlertActionStyleDestructive
handler:^(UIAlertAction * action)
{
[view dismissViewControllerAnimated:YES completion:nil];
}];
Ответ 8
UIAlertController имеет доступ к iOS 8 и более поздним версиям, поэтому есть ошибка для устройств со старой версией. Нет проблем для устройств с соответствующей или более высокой версией.
Ответ 9
Чтобы предотвратить быстрое "всплытие" нового оттенка, альфа-значение контроллера предупреждения может быть анимировано. Тогда он выглядит точно так же, как если бы там не было ошибок:
alertController.view.alpha = 0.0
presentViewController(alertController, animated: false) {
alertController.view.tintColor = UIColor.redColor()
UIView.animateWithDuration(0.2, animations: { alertController.view.alpha = 1.0 }, completion: nil)
}
Ответ 10
Чтобы настроить пользовательский цвет и шрифт подкласс UIAlertController
следующим образом.
import UIKit
class StyledAlertController: UIAlertController {
private var cancelText:String?
override func viewDidLoad() {
super.viewDidLoad()
view.tintColor = YourColor
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
findLabel(view)
}
private func findLabel(scanView: UIView!) {
if (scanView.subviews.count > 0) {
for subview in scanView.subviews {
if let label:UILabel = subview as? UILabel {
if (cancelText != nil && label.text == cancelText!) {
dispatch_async(dispatch_get_main_queue(),{
label.textColor = YourColor
label.tintColor = YourColor
})
}
let font:UIFont = UIFont(name: YourFont, size: label.font!.pointSize)!
label.font = font
}
findLabel(subview)
}
}
}
}
Используйте это (как обычно)
let StyledAlertController = StyledAlertController(title: "My Title", message: "My Message", preferredStyle: .ActionSheet)
let cancelAction:UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
print("Cancel Action Click")
}
actionSheetController.addAction(cancelAction)
let anotherAction:UIAlertAction = UIAlertAction(title: "Another Action", style: .Default) { action -> Void in
print("Another Action Click")
}
actionSheetController.addAction(anotherAction:UIAlertAction)
presentViewController(actionSheetController, animated: true, completion: nil)