![](/img/trans.png)
[英]Swift: Array property with elements conforming to a class and multiple protocols simultaneously
[英]Swift property conforming with multiple protocols
我有符合兩個不同協議的自定義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 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?
}
有什么辦法讓兩個人只有一個同時符合這兩個協議的委托屬性? 我正在使用Swift 2.0,Xcode 7。
我想您真的不需要聲明Resizable
和Tappable
協議。 您需要做的就是將您的自定義視圖委托給其他對象,該對象可以同時確認ResizableDelegate
和TappableDelegate
,對嗎? 如果是這樣,這應該為您工作:
protocol ResizableDelegate: class {
func view(view:UIView, didChangeHeight difference:CGFloat)
}
protocol TappableDelegate: class {
func viewDidTap(view:UIView)
}
class CustomView : UIView {
var delegate: (ResizableDelegate, TappableDelegate)?
}
盡管您可以保留原樣,但我強烈建議您將所需屬性更改為“ tappableDelegate”和“ resizableDelegate”,這樣在View子類中就有兩個單獨的屬性。
您的特定用例可能需要同時遵循兩者,但是使用相同的命名意味着您將無法擁有不同的委托。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.