如何将协议types添加为子视图

所以我写了一个简单的协议:

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

并有一个customView:

 class XYZMessageView: UIView, PopupMessageType { ... } 

然后我现在有:

 class PopUpViewController: UIViewController { //code... var messageView : CCPopupMessageView! private func setupUI(){ view.addSubview(messageView) } } 

但是我想要做的是:

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

错误我得到:

无法转换types“PopupMessageType!”的值 到期望的参数types“UIView”

编辑:我在Swift 2.3!

在Swift 4中你可以这样做:

 typealias PopupMessageViewType = UIView & PopupMessageType 

然后使用PopupMessageViewType作为variables的types。

将属性messageView的types更改为(UIView&PopupMessageType)!

我的意思是

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

免责声明:我没有swift 2.3编译器,因为swift 4是iOS开发的新常态。 下面的代码可能需要调整,以使其迅速2.3工作


本质上,我们将制作一个2×1多路复用器,其中两个input是相同的对象。 输出取决于您是否将复用器设置为select第一个还是第二个。

 // The given protocol protocol PopupMessageType{ var cancelButton: UIButton {get set} func cancel() } // The object that conforms to that protocol class XYZMessageView: UIView, PopupMessageType { var cancelButton: UIButton = UIButton() func cancel() { } } // The mux that lets you choose the UIView subclass or the PopupMessageType struct ObjectPopupMessageTypeProtocolMux<VIEW_TYPE: UIView> { let view: VIEW_TYPE let popupMessage: PopupMessageType } // A class that holds and instance to the ObjectPopupMessageTypeProtocolMux class PopUpViewController: UIViewController { var messageWrapper : ObjectPopupMessageTypeProtocolMux<UIView>! private func setupUI(){ view.addSubview(messageWrapper.view) } } //... let vc = PopUpViewController() // create the view controller let inputView = XYZMessageView() // create desired view // create the ObjectPopupMessageTypeProtocolMux vc.messageWrapper = ObjectPopupMessageTypeProtocolMux(view: inputView, popupMessage: inputView) //<-- 1 vc.messageWrapper.view // retreive the view vc.messageWrapper.popupMessage.cancel() // access the protocol's methods vc.messageWrapper.popupMessage.cancelButton // get the button 

1)我为ObjectPopupMessageTypeProtocolMux的初始化程序input两次“inputView”。 它们是同一个类实例,但是它们被转换为不同的types。

我希望这可以帮助你快速到达2.3的地方