UIAlertController change background color of Cancel button for action sheet

后端 未结 5 1130
死守一世寂寞
死守一世寂寞 2020-12-18 15:38

I am trying to create a UIAlertController with the action sheet style but I want to change the background color to a gray color. I have been able to find a way to change the

5条回答
  •  鱼传尺愫
    2020-12-18 16:31

    You cannot change color of a default cancel button style. You need to create a custom view controller for the cancel button and set it as a content view controller of a cancel alert action. This way keeps the cancel button separately

    let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    
    alertController.addAction(UIAlertAction(title: "Option 1", style: .default, handler: nil))
    alertController.addAction(UIAlertAction(title: "Option 2", style: .default, handler: nil))
    alertController.addAction(UIAlertAction(title: "Option 3", style: .default, handler: nil))
    
    alertController.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: nil))
    
    if let firstSubview = alertController.view.subviews.first, let alertContentView = firstSubview.subviews.first {
        for view in alertContentView.subviews {
            view.backgroundColor = .darkGray
        }
    }
    
    alertController.view.tintColor = .white
    
    let cancelButtonViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CancelButtonViewController")
    let cancelAction = UIAlertAction(title: "", style: .cancel, handler: nil)
    cancelAction.setValue(cancelButtonViewController, forKey: "contentViewController")
    
    alertController.addAction(cancelAction)
    
    present(alertController, animated: true, completion: nil)
    

提交回复
热议问题