1

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

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

    }

}

错误我得到:

无法转换类型“PopupMessageType!”的值 到预期的参数类型'UIView'

编辑: 我在 Swift 2.3 上!

4

3 回答 3

3

将属性messageView的类型改为( UIView & PopupMessageType)!

我是说

class PopUpViewController: UIViewController {

    //code...

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

    }

}
于 2017-10-09T18:52:07.933 回答
2

免责声明:我不再拥有 swift 2.3 编译器,因为 swift 4 是 iOS 开发的新常态。以下代码可能需要调整才能在 swift 2.3 中运行


本质上,我们将制作一个 2x1 多路复用器,其中两个输入是同一个对象。输出取决于您将多路复用器设置为选择第一个还是第二个。

// 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的初始化程序输入了两次“inputView”。它们是相同的类实例,但它们被强制转换为不同的类型。

我希望这可以帮助您在 swift 2.3 中到达您想去的地方

于 2017-10-09T19:49:31.290 回答
2

在 Swift 4 中,您可以这样做:

typealias PopupMessageViewType = UIView & PopupMessageType

然后PopupMessageViewType用作变量的类型。

于 2017-10-09T18:52:42.200 回答