UIAlertController动作表whatsapp风格

时间:2016-11-14 09:12:17

标签: ios whatsapp uiactionsheet uialertaction

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

enter image description here

2 个答案:

答案 0 :(得分:5)

嗯,作为上述讨论的结果,找到了一个解决方案。 基本思想是使用" 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)

    }

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 in storyboard

a screenshot

答案 1 :(得分:0)

是的,您需要向UIAlertController添加UITableView。

alertController.setValue([customTableGoesHere], forKey: "contentViewController")