UIAlertController动作表whatsapp风格

Ben*_*itz 2 uiactionsheet ios whatsapp uialertaction

有没有人知道如何创建一个UhalertController,就像whatsapp在下一个附件中所做的那样(除了创建自定义UI之外)

在此输入图像描述

Ben*_*itz 6

好吧,作为上述讨论的结果,找到了一个解决方案.基本思路是使用"contentViewController"

实施smaple

ViewController.swift

@IBAction func testActionSheetAction(_ sender: Any) {

        let sheet = UIAlertController(title: "test", message: nil, preferredStyle: .actionSheet)

        let phoneAction = UIAlertAction(title: "", style: .default) { (_) in
            print("phone action")
        }
        phoneAction.mode = .phone
        sheet.addAction(phoneAction)

        let homeAction = UIAlertAction(title: "", style: .default) { (_) in
            print("home action")
        }
        homeAction.mode = .home

        sheet.addAction(homeAction)

        sheet.addAction(UIAlertAction(title: "cancel", style: .cancel, handler: nil))

        self.present(sheet, animated: true, completion: nil)

    }
Run Code Online (Sandbox Code Playgroud)

ActionSheetContentViewController.swift

import UIKit

extension UIAlertAction{
    var mode : ActionSheetContentViewController.Mode?{
        set{
            let vc = ActionSheetContentViewController.viewController(with: newValue)
            self.setValue(vc, forKey: "contentViewController")
        }
        get{
            if let vc = value(forKey: "contentViewController") as? ActionSheetContentViewController{
                return vc.mode
            }

            return nil
        }
    }
}

class ActionSheetContentViewController: UIViewController {

    enum Mode{
        case home
        case phone

        var image : UIImage{
            get{
                switch self {
                case .home: return #imageLiteral(resourceName: "icon_home")
                case .phone: return #imageLiteral(resourceName: "icon_phone")
                }
            }
        }

        var title : String{
            get{
                switch self {
                case .home: return NSLocalizedString("home", comment: "home")
                case .phone: return NSLocalizedString("phone", comment: "phone")
                }
            }
        }
    }

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var imaegView: UIImageView!

    var mode : Mode?

    override func viewDidLoad() {
        super.viewDidLoad()

        label.text = mode?.title
        imaegView.image = mode?.image
    }

    class func viewController(with mode : Mode?) -> UIViewController{

        let storyboard = UIStoryboard(name: "Main", bundle: .main)
        let vc = storyboard.instantiateViewController(withIdentifier: "ActionSheetContentViewController") as! ActionSheetContentViewController

        vc.mode = mode

        return vc

    }
}
Run Code Online (Sandbox Code Playgroud)

故事板中的ActionSheetContentViewController

截图

  • 据我所知,“contentViewController”的 KVCing 不是私有 API,但它是未记录的 API,这意味着您必须针对您所针对的所有 iOS 版本验证它。您可以自己验证这不是私有 API(产品->存档,然后“验证...”) (2认同)