2

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

4

1 回答 1

3

我尝试并搜索了很多,终于找到了答案。这里是:

**使用图标创建`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 带有取消按钮和 3 个带有图标的条目


**为条目着色**

然后我尝试为所有内容着色,并在实例化下面添加了以下行UIAlertController: optionMenu.view.tintColor = Colors.getColors().primaryTintColor

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

iOS8
使用 iOS8 着色 UIAlertController

iOS9
使用 iOS9 着色 UIAlertController

**解决方案**

我花了很长时间,但后来我找到了解决方案。您必须呈现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
于 2016-08-30T06:56:07.237 回答