2016-06-12 185 views
2

我希望協議從繼承來自Apple協議UIViewControllerTransitioningDelegate,添加其他協議要求併爲該協議中的某些方法提供默認實現。當我這樣做時,方法不會被調用。當我在類中實現方法時,方法被調用。當協議擴展現有的Apple API協議時,不會調用協議擴展方法

這裏就是我說的:

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

我也嘗試過爲UIView提供默認實現ControllerTransitioningDelegate' – Mingming

回答

1

我有同樣的問題,試圖做類似的事情。顯然目前的協議擴展限制似乎是我們不能提供Objective-C協議的默認實現。因此,在UIKit中聲明的任何協議都屬於這個類別。這也是關於面向協議編程的以下建議article。 這是9月2016年 的有效我覺得你的痛苦=(但我想現在這種清潔劑推廣方法不是暫時真的可行

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 
    } 
}