swift2 如何将协议类型添加为子视图

2hh7jdfx  于 2022-11-06  发布在  Swift
关注(0)|答案(3)|浏览(162)

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

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!

w6lpcovy

w6lpcovy1#

将属性类型消息视图更改为**(UI视图和弹出消息类型)!**
我的意思是

class PopUpViewController: UIViewController {

    //code...

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

    }

}
neskvpey

neskvpey2#

在Swift 4中,您可以执行以下操作:

typealias PopupMessageViewType = UIView & PopupMessageType

然后使用PopupMessageViewType作为变量的类型。

suzh9iv8

suzh9iv83#

免责声明:我已经没有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中达到你想达到的目标

相关问题