您可以扩展myOwnViewController,告诉扩展符合UINavigationControllerDelegate 协议并实现您想要的方法,但这并不能取代委托模式。如果您的扩展不符合此委托的协议,您将无法将myOwnViewController 附加为UINavigationController's 委托。
class MyController: UIViewController {
}
extension MyController: UINavigationControllerDelegate {
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return .Portrait
}
}
let navigationController = UINavigationController()
let controller = MyController()
navigationController.delegate = controller
告诉MyController类符合UINavigationControllerDelegateprotocol可以达到同样的效果。
class MyController: UIViewController, UINavigationControllerDelegate {
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return .Portrait
}
}
let navigationController = UINavigationController()
let controller = MyController()
navigationController.delegate = controller
这两个示例导致MyController 成为您的UINavigationController 的代表。这可能导致在一个地方承担许多责任。为了分担此责任,您可以创建另一个类作为导航控制器的委托。
class MyController: UIViewController {}
class NavigationDelegate: NSObject, UINavigationControllerDelegate {
func navigationControllerSupportedInterfaceOrientations(navigationController: UINavigationController) -> UIInterfaceOrientationMask {
return .Portrait
}
}
let navigationController = UINavigationController()
let controller = MyController()
let navigationDelegate = NavigationDelegate()
navigationController.delegate = navigationDelegate
有什么区别?想象一下,你已经为你支持的方向方法实现了一个复杂的逻辑,你发现你不再使用MyController,而是使用DifferentController。由于您的方向逻辑位于MyController 中,因此无论如何您都需要创建它。但是,如果您的委托逻辑在 NavigationDelegate 类中分离,您可以使用 DifferentController 而无需仅为这些委托方法创建 MyController 类。