关于Delegate设计模式. From Hacking with Swift, Project 4.
Delegate,英语有两个词性,
一个是动词,
及物动词: 委派,委托。to delegate sth. to sb. OR to delegate sb. to do sth.
不及物动词: 授权. a goog manager knows how to delegate
一个是名词, 代表。
A delegate is one thing acting in place of another, effectively answering questions and responding to events on its behalf. In our example, we're using WKWebView: Apple's powerful, flexible and efficient web renderer. But as smart as WKWebView is, it doesn't know (or care!) how our application wants to behave, because that's our custom code.
一个代表(delegate)就是代表,代替某个事物本身行使某些动作,响应某些事件。为啥需要让别的东西代表它自己呢?因为一个定制好的模块/组件/控件如何响应事件,每个开发者都有不一样的需求。比如WKWebView,在加载页面的时候,怎样告知用户加载进度?有的需求希望用一个进度条往前走,有的用一个转菊转啊转。那么这个就可以由一个代表去实现。原文是:就算是像WKWebView这么牛x,它也不知道在应用要求它有些啥行为,因为这是我们定制的代码。
The delegation solution is brilliant: we can tell WKWebView that we want to be told when something interesting happens. In our code, we're setting the web view's navigation Delegate property to self, which means "when any web page navigation happens, please tell me."
这个委托方案的牛x之处在于: 我们可以告诉WKWebView, 当我们感兴趣的事儿发生的时候,我们需要被通知到。比如,这里设置webview的代表为我们自己的ViewController. 就是委托ViewController来处理网页浏览时发生的事件。
When you do this, two things happen:
You must conform to the protocol. This is a fancy way of saying, "if you're telling me you can handle being my delegate, here are the methods you need to implement." In the case of navigation Delegate, all these methods are optional, meaning that we don't need to implement any methods.
Any methods you do implement will now be given control over the WKWebView's behavior. Any you don't implement will use the default behavior of WKWebView.
那么,要这么做,2件事儿:
1. 你要遵从协议。所谓协议,就是要实现事先约定的一些接口(Interface)。这些接口是在Delegate这个object里定义的。代码上就是extends这个delegate接口。所有的interface都是可选的,也就是我们不必实现所有的interface。如果不实现,就说明你要用WKWebView默认的行为.