ios - 符合多种协议(protocol)的 Swift 属性

标签 ios swift swift-protocols

我有符合两种不同协议(protocol)的自定义 UIView (CustomView)

protocol ResizableDelegate: class {
    func view(view:UIView, didChangeHeight difference:CGFloat)
}
protocol Resizable: class {
    var delegate:ResizableDelegate? { set get }
}


protocol TappableDelegate: class {
    func viewDidTap(view:UIView)
}
protocol Tappable {
    var delegate:TappableDelegate? { set get }
}

我需要在我的 CustomView 类中有一个名为 delegate 的属性,并且同时符合这两个协议(protocol)。我读了Types conforming to multiple protocols in swift但这并不能解决我的问题。

我创建了这个协议(protocol)

protocol CustomViewDelegate: ResizableDelegate, TappableDelegate {}

然后制作我的CustomView

class CustomView : UIView, Resizable, Tappable {
    var delegate:CustomViewDelegate?
}

但这导致我收到一条消息

Type 'CustomView' does not conform to protocol 'Resizable'

我不想拥有:

class CustomView : UIView, Resizable, Tappable {
   var resizableDelegate:ResizableDelegate?
   var TappableDelegate:TappableDelegate?
}

有没有办法让两者只有一个委托(delegate)属性同时符合这两个协议(protocol)?我使用的是 swift 2.0,Xcode 7。

最佳答案

我猜你真的不需要声明 ResizableTappable 协议(protocol)。您所需要做的就是从您的自定义 View 委托(delegate)给其他对象,这会确认 ResizableDelegateTappableDelegate,对吗?如果是这样,这应该对您有用:

protocol ResizableDelegate: class {
    func view(view:UIView, didChangeHeight difference:CGFloat)
}

protocol TappableDelegate: class {
    func viewDidTap(view:UIView)
}

class CustomView : UIView {
    var delegate: (ResizableDelegate, TappableDelegate)?

}

关于ios - 符合多种协议(protocol)的 Swift 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40474519/

相关文章:

swift - 如何运行 swift XCTest tearDown 一次

ios - UIPopoverPresentationController 显示为全窗口弹出

swift - 在 Swift 中,Objective-C 类的属性是否有可能满足 Swift @obj 协议(protocol)计算属性要求?

ios - swift 。公共(public)协议(protocol)中的内部类型

ios - 多点连接 :List all nearby sessions

ios - 如何在动态创建的文本字段中设置 ScrollView 的内容偏移量?

ios - 4 英寸 iPhone 中的 uitableviewcell uiimage 自动布局问题

ios - 协议(protocol)扩展中的默认值

ios - SKMaps 注释顺序(z 索引)

ios - iOS 应用程序可以有登录屏幕吗?