我的故事板中有一个ViewController,它的工作方式类似于警报(带有标题、消息和两个按钮)。
我想将它封装起来,以便能够在我的代码中的任何地方使用它,例如:

let alert = CustomAlertViewController(title: "Test", message: "message de test.", view: self.view, delegate: self)
self.present(alert, animated: false, completion: nil)

我的问题是IBOutlets没有初始化。。。
我的自定义警报视图控制器:
public protocol CustomAlertProtocol {
    func alertAccepted()
}

class CustomAlertViewController: UIViewController {

    var delegate :CustomAlertProtocol? = nil
    var parentView :UIView?
    var blurScreenshot :SABlurImageView?

    var alertTitle :String? = nil
    var alertMessage :String? = nil

    @IBOutlet weak var oAlertView: UIView!
    @IBOutlet weak var oAlertTitle: UILabel!
    @IBOutlet weak var oAlertMessage: UILabel!


    //MARK: - Main

    public convenience init(title: String?, message: String?, view: UIView, delegate: CustomAlertProtocol) {
        self.init()
        self.alertTitle = title
        self.alertMessage = message
        self.delegate = delegate
        self.parentView = view
    }

    override func viewDidLoad() {
        oAlertTitle.text = self.alertTitle
        oAlertMessage.text = self.alertMessage
    }

    @IBAction func onAcceptButtonPressed(_ sender: AnyObject) {
        delegate?.alertAccepted()
    }
}

最佳答案

将视图控制器的Custom Class属性设置为CustomAlertViewController
以及Storyboard ID到您想要的任何地方-例如,在InterfaceBuilder的身份检查器中。
然后将其实例化如下:

let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())

guard let vc = storyboard.instantiateViewControllerWithIdentifier("CustomAlertViewControllerIdentifier") as? CustomAlertViewController else {
    return
}

编辑:
然后可以将该代码放入类函数中,如:
extension CustomAlertViewController {
    class func instantiateFromStoryboard(title: String?, message: String?, view: UIView, delegate: CustomAlertProtocol) -> CustomAlertViewController {
        let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
        let vc = storyboard.instantiateViewControllerWithIdentifier("CustomAlertViewControllerIdentifier") as! CustomAlertViewController

        vc.title = title
        vc.message = message
        vc.view = view
        vc.delegate = delegate

        return vc
    }
}

然后使用如下:
let myCustomAlertViewController = CustomAlertViewController.instantiateFromStoryboard(title: "bla", ...)

关于ios - 如何在Swift中封装UIViewController(如UIAlertController)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40259623/

10-13 03:49