如何在UIAlertController中为UIImage着色

时间:2016-08-30 06:56:07

标签: swift ios8 ios9 uialertcontroller uialertaction

如何创建带有取消按钮的UIAlertController和带图标的其他三个按钮?我支持iOS 8向上。 每个条目都应该着色......

1 个答案:

答案 0 :(得分:2)

我经常尝试和搜索,最后找到答案。这是:

**用图标创建`UIAlertController`:**

重要的部分是添加action1.setValue(UIImage(named: "Icon1"), forKey: "image")

的图标
let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)

let action1 = UIAlertAction(title: "Test 1", style: .Default, handler: {
    [unowned self] (alert: UIAlertAction!) -> Void in
    print("Action 1")
})
action1.setValue(UIImage(named: "Icon1"), forKey: "image")

let action2 = UIAlertAction(title: "Test 2", style: .Default, handler: {
    [unowned self] (alert: UIAlertAction!) -> Void in
    print("Action 2")
})
action2.setValue(UIImage(named: "Icon2"), forKey: "image")

let action3 = UIAlertAction(title: "Test 3", style: .Default, handler: {
    [unowned self] (alert: UIAlertAction!) -> Void in
    print("Action 3")
})
action3.setValue(UIImage(named: "Icon3"), forKey: "image")

let cancelAction = UIAlertAction(title: "Close", style: .Cancel, handler: nil)

optionMenu.addAction(action1)
optionMenu.addAction(action2)
optionMenu.addAction(action3)
optionMenu.addAction(cancelAction)

presentViewController(optionMenu, animated: true, completion: nil)

这就是我得到的。好到目前为止

UIAlertController with cancel button and 3 entries with icon

**着色条目**

然后我尝试着色一切,并在UIAlertController的实例化下面添加了以下行:     optionMenu.view.tintColor = Colors.getColors()。primaryTintColor

iOS8看起来相当不错,但是当我用iOS9测试相同的代码时,我感到很惊讶(本地化的差异是因为模拟器中的设置不同):

<强> iOS8上
Tinted UIAlertController with iOS8

<强> iOS9
Tinted UIAlertController with iOS9

**解决方案**

我花了很长时间,但后来我找到了解决方案。 您必须在之后设置色调颜色以显示UIAlertController

这是最终代码:

let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)

let action1 = UIAlertAction(title: "Test 1", style: .Default, handler: {
    [unowned self] (alert: UIAlertAction!) -> Void in
    print("Action 1")
})
action1.setValue(UIImage(named: "Icon1"), forKey: "image")

let action2 = UIAlertAction(title: "Test 2", style: .Default, handler: {
    [unowned self] (alert: UIAlertAction!) -> Void in
    print("Action 2")
})
action2.setValue(UIImage(named: "Icon2"), forKey: "image")

let action3 = UIAlertAction(title: "Test 3", style: .Default, handler: {
    [unowned self] (alert: UIAlertAction!) -> Void in
    print("Action 3")
})
action3.setValue(UIImage(named: "Icon3"), forKey: "image")

let cancelAction = UIAlertAction(title: "Close", style: .Cancel, handler: nil)

optionMenu.addAction(action1)
optionMenu.addAction(action2)
optionMenu.addAction(action3)
optionMenu.addAction(cancelAction)

presentViewController(optionMenu, animated: true, completion: nil)
optionMenu.view.tintColor = Colors.getColors().primaryTintColor