Search code examples
iosswiftswift2swift-protocolsprotocol-oriented

How to add protocol type as subview


So I wrote a simple protocol:

protocol PopupMessageType{
    var cancelButton: UIButton {get set}
    func cancel()
}

and have a customView:

class XYZMessageView: UIView, PopupMessageType {
...
}

and then I currently have:

class PopUpViewController: UIViewController {

    //code...

    var messageView : CCPopupMessageView!
    private func setupUI(){
    view.addSubview(messageView)

    }

}

But what I want to do is:

class PopUpViewController: UIViewController {

    //code...

    var messageView : PopupMessageType!
    private func setupUI(){
    view.addSubview(messageView) // ERROR

    }

}

ERROR I get:

Cannot convert value of type 'PopupMessageType!' to expected argument type 'UIView'

EDIT: I'm on Swift 2.3!


Solution

  • Change the type of property messageView to (UIView & PopupMessageType)!

    I mean

    class PopUpViewController: UIViewController {
    
        //code...
    
        var messageView : (UIView & PopupMessageType)!
        private func setupUI(){
        view.addSubview(messageView) // ERROR
    
        }
    
    }