所以我有一个viewController,它拥有一个自定义视图,
viewController类符合 ViewProtocol
ViewProtocol
我想什么时候 someAction 方法在中触发 someCustomizedView
someAction
someCustomizedView
它会打印出来 " method in otherCustomizedClass called "
" method in otherCustomizedClass called "
但它会打印 (" method in extension Called") 相反
(" method in extension Called")
这个 theNotOptionalMethod 效果很好,但不是可选方法。
theNotOptionalMethod
我对协议扩展有什么误解吗?
请帮忙,已经挣扎了好几个小时了,谢谢
protocol ViewDelegate: class { func theNOTOptionalMethod() } extension ViewDelegate { func theOptionalMethod(){ print (" method in extension Called") } } class someCustomizedView: UIView { weak var deleage: ViewDelegate? @IBAction func someAction(sender: UIButton) { deleage?.theOptionalMethod() } } class someCustomizedVC: UIViewController, ViewDelegate { lazy var someView: someCustomizedView = { var v = someCustomizedView() v.deleage = self return v }() //...... someView added to controller func theNOTOptionalMethod() { // do nothing } func theOptionalMethod() { print (" method in otherCustomizedClass called ") } }
扩展中的方法就是这样工作的。它们将实现隐藏在类中。
要使用可选方法创建协议,需要将可选方法放入协议定义中:
protocol ViewDelegate: class { func theNOTOptionalMethod() func theOptionalMethod() }
或者,你可以使用 @objc 和 optional 修饰语:
@objc
optional
@objc protocol MyDelegate : class{ func notOptionalMethod() @objc optional func optionalMethod() }
当你打电话的时候 optionalMethod ,您需要打开可选的:
optionalMethod
delegate.optionalMethod?()