About iOS programming: Delegate

关于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默认的行为.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 今天看《一转成双》都要炸了。恨不能冲进屏幕里冲着那位阿姨咆哮:“这样的男人还不离婚,是留着过年吗?” 事情原由是这...
    宁果0619阅读 649评论 2 7
  • 读的什么书:《如何高效阅读》 阅读有效时间:半小时 阅读中遇到的困难:里面的练习题,操作难度有点大 阅读有什么收获...
    冥王hardess阅读 107评论 0 0
  • 生活本就淡如水,但是却又无比丰富。我们在生活里重复,重复着每天的事,每天的话,每天的动作,每天的行为,甚至于每天的...
    呼吸的鲸鱼阅读 267评论 0 0
  • 【引言】 《泰伯》21章,论及孔子道德思想的具体内容和曾子在好多问题上的见解,通过对尧舜禹等先王评价,进一...
    钱江潮369阅读 645评论 0 2