2

有谁知道如何创建一个 UIAlertController 就像 whatsapp 在下一个附件中所做的那样(除了创建自定义 UI)

在此处输入图像描述

4

2 回答 2

6

好吧,作为上述讨论的结果,找到了解决方案。基本思想是使用“contentViewController”

实施样本

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)

    }

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

    }
}

故事板中的 ActionSheetContentViewController

截图

于 2017-08-03T15:38:39.273 回答
0

是的,您需要将 UITableView 添加到 UIAlertController。

alertController.setValue([customTableGoesHere], forKey: "contentViewController")
于 2017-07-23T20:04:09.057 回答