我希望协议能够从Apple协议UIViewControllerTransitioningDelegate
继承,添加其他协议要求并为该协议中的某些方法提供默认实现。当我这样做时,方法不会被调用。当我在类本身中实现方法时,方法 do 被调用。
这就是我所说的:
class FirstViewController: UIViewController, SlideDismissor {
let transition: PercentDrivenInteractiveTransitionWithState? = PercentDrivenInteractiveTransitionWithState()
}
protocol SlideDismissor: UIViewControllerTransitioningDelegate {
var transition: PercentDrivenInteractiveTransitionWithState? { get }
}
extension SlideDismissor {
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return nil // I do return something here, but for this example it isn't necessary
}
func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return transition
}
}
如果我添加以下代码,则会调用函数。
extension FirstViewController: UIViewControllerTransitioningDelegate {
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return nil // I do return something here, but for this example it isn't necessary
}
func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return transition
}
}
我试图提供默认实现的这些方法是可选方法。
答案 0 :(得分:2)
针对这些问题的更好解决方案是使用组合而不是继承。而不是符合SlideDismissor
,委托给一个。
(我还没有对这段代码进行测试,甚至确保编译,但这是我要探索的基本方法。)
class FirstViewController: UIViewController {
// Rather than handle your own transitioning, delegate it to another, reusable, object.
override func viewDidLoad() {
// Your original protocol suggested that the view controller wanted
// to control what kind of transition was used, so we pass it as a paramater.
transitioningDelegate = SlideDismissor(transition: PercentDrivenInteractiveTransitionWithState())
}
}
// In that object, implement all the delegate methods
class SlideDismissor: NSObject, UIViewControllerTransitioningDelegate {
let transition: PercentDrivenInteractiveTransitionWithState?
init(transition: PercentDrivenInteractiveTransitionWithState?) {
self.transition = transition
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return nil // I do return something here, but for this example it isn't necessary
}
func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return transition
}
}
答案 1 :(得分:1)
我有同样的问题试图做类似的事情。显然,协议扩展的当前限制似乎是我们无法提供Objective-C协议的默认实现。因此,在UIKit中声明的任何协议都属于这一类。对于面向协议的编程,还提出了以下建议的article。 这个有效期截至2016年9月。 我觉得你的痛苦=(但我想现在这种更清洁的扩展方法暂时不可行