關(guān)于Delegate設(shè)計(jì)模式. From Hacking with Swift, Project 4.
Delegate胶背,英語有兩個(gè)詞性巷嚣,
一個(gè)是動(dòng)詞,
及物動(dòng)詞: ? 委派廷粒,委托。to delegate sth. to sb. ?OR to delegate sb. to do sth.
不及物動(dòng)詞: 授權(quán). a goog manager knows how to delegate
一個(gè)是名詞, 代表红且。
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.
一個(gè)代表(delegate)就是代表坝茎,代替某個(gè)事物本身行使某些動(dòng)作暇番,響應(yīng)某些事件嗤放。為啥需要讓別的東西代表它自己呢?因?yàn)橐粋€(gè)定制好的模塊/組件/控件如何響應(yīng)事件壁酬,每個(gè)開發(fā)者都有不一樣的需求次酌。比如WKWebView恨课,在加載頁面的時(shí)候,怎樣告知用戶加載進(jìn)度岳服?有的需求希望用一個(gè)進(jìn)度條往前走剂公,有的用一個(gè)轉(zhuǎn)菊轉(zhuǎn)啊轉(zhuǎn)。那么這個(gè)就可以由一個(gè)代表去實(shí)現(xiàn)纲辽。原文是:就算是像WKWebView這么牛x,它也不知道在應(yīng)用要求它有些啥行為璃搜,因?yàn)檫@是我們定制的代碼。
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."
這個(gè)委托方案的牛x之處在于: 我們可以告訴WKWebView, 當(dāng)我們感興趣的事兒發(fā)生的時(shí)候绿贞,我們需要被通知到因块。比如,這里設(shè)置webview的代表為我們自己的ViewController. 就是委托ViewController來處理網(wǎng)頁瀏覽時(shí)發(fā)生的事件趾断。
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. 你要遵從協(xié)議。所謂協(xié)議脐帝,就是要實(shí)現(xiàn)事先約定的一些接口(Interface)堵腹。這些接口是在Delegate這個(gè)object里定義的。代碼上就是extends這個(gè)delegate接口星澳。所有的interface都是可選的疚顷,也就是我們不必實(shí)現(xiàn)所有的interface。如果不實(shí)現(xiàn)禁偎,就說明你要用WKWebView默認(rèn)的行為.