如何在特定操作表上更改UIAlertController上的字体颜色?

时间:2018-04-27 01:42:33

标签: ios swift uialertcontroller

enter image description here

我可以使用下面的代码将所有动作的字体颜色更改为绿色,如上图所示:

func showAlertSheet() {
    let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

    let accountAction = UIAlertAction(title: "Account", style: .default) { (action) in
        self.performSegue(withIdentifier: "toAccountVC", sender: nil)
    }

    let actionPhotoLibrary = UIAlertAction(title: "Logout", style: .default) { (action) in

    }

    let actionCancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)


    actionSheet.addAction(accountAction)
    actionSheet.addAction(actionPhotoLibrary)
    actionSheet.addAction(actionCancel)

    actionSheet.view.tintColor = UIColor(red: 0/255, green: 129/255, blue: 58/255, alpha: 1)

    self.present(actionSheet, animated: true, completion: nil)
}

但我需要将Logout操作更改为红色,如下图所示 enter image description here

我已阅读此帖子UIAlertController custom font, size, color,但我找不到在特定UIAlertController操作表上更改字体颜色的方法。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

使用.destructive代替.default作为动作样式。

答案 1 :(得分:0)

没有直接的方法来设置操作表上的特定按钮。你可以这样做,让它开心。

  1. 创建一个自定义的UIAlertController子类,让它称之为TestAlertController。
  2. 覆盖viewDidAppear方法以查找要修改的标签。
  3. 只需使用TestAlertController。
  4. 以下是ipod(ios 9.3)中的代码,您可以尝试一下。

    class TestAlertController: UIAlertController {
        override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        let subViews = self.view.subviews[0].subviews[1].subviews[0].subviews
        for view in subViews {
            if view.isKind(of: NSClassFromString("UICollectionView")!) {
                if let modifyView = view.subviews[1].subviews[0].subviews[0].subviews[0].subviews[0] as? UILabel {
                    print(modifyView)
                    modifyView.tintColor = UIColor.red
                }
            }
        }
    }
    }
    

    但它在iPhone8加模拟器(iOS 11)中有所不同,代码为:

        override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if #available(iOS 9.0, *) {
            if let stackView = self.view.subviews[0].subviews[0].subviews[1].subviews[1].subviews[0].subviews[0] as? UIStackView {
                let view = stackView.arrangedSubviews[2]
                if let label = view.value(forKeyPath: "_actionContentView._label") as? UILabel {
                    label.tintColor = UIColor.red
                }
                print("hard to locate...")
            }
        }
    }
    

    这是屏幕截图: enter image description here

    此方法需要检查每个iOS版本或iPhone。我认为这不是一个好方法。但我无法找到更好的方法。谁能告诉我一个更好的方法呢?