Swift 3代表的例子 [英] Examples of Delegates in Swift 3

查看:122
本文介绍了Swift 3代表的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试学习协议如何工作。我明白了一切,但我不能想到什么时候使用代理,而不是使用表视图和可能的滚动视图。

I have been trying to learn how delegation with protocols work. I understood everything, but I can't think of when to use delegation other than when using table views and possibly scroll views.

一般来说,什么时候使用委托? / p>

In general, when is delegation used?

推荐答案

什么是代表团?



首先,你应该知道授权模式不是专属于iOS世界的:

What is Delegation?

First of all, you should know that Delegation Pattern is not exclusive for iOS world:


在软件工程中,委托模式是
面向对象编程中的设计模式,允许对象组合实现
与继承相同的代码重用。 / p>

In software engineering, the delegation pattern is a design pattern in object-oriented programming that allows object composition to achieve the same code reuse as inheritance.

但是使用在iOS世界中的代理是很常见的,我假设你可以看到许多提供授权/ atasource用于提供为使用实例提供属性或行为的能力。它是CocoaTouch中对象之间如何对话的主要机制之一。

But working with delegation in the iOS world is so common, I assume that you can see many of classes that provide a delegation/datasource for giving the ability to provide properties or behaviors for the used instance. It is one of main mechanisms of how objects talk to each other in CocoaTouch.

但是,代理不是,只是让对象在iOS中互相交流,您可能想知道有:

However, delegation is not the only way to let objects talk to each others in iOS, you might want to know that there are:

  • NotificationCenter.
  • KVO (Key-Value Observing).
  • Completion handlers/Callbacks (using closures).
  • Target-Action.

备注:如果您有兴趣比较他们,您可能需要检查以下文章:

Remark: in case if you are interested in comparing between them, you might want to check the following articles:

  • Communication Patterns.
  • When to Use Delegation, Notification, or Observation in iOS.
  • Delegates vs Observers.

问题是:那么为什么要使用代理而不是这些选项?

So, the question is: "So why should I use delegation instead of those options?"

我会尽量简化;当您有两个对象之间的 一对一 关系时,我建议使用委派。只是为了使之更清楚,关于通知中心的目标是要尝试使用代表团:

I will try to make it simple; I would suggest to use delegation when you have one to one relationship between two objects. Just to make it clearer, the goal of talking a little bit about the NotificationCenter is to trying to make sense when to use delegations:

NotificationCenter 表示 一对多 关系;简单来说,它的工作原理如下:发布(通知)关于特定事件的通知和观察(获取通知)这个通知,可以在任何地方观察其他在逻辑上,这是一对多关系的意思。它是观察者模式的表示。

NotificationCenter represents one to many relationship; Simply, It works as: posting (notifying) a notification on a specific event and observing (get notified) this notification, it could be observed anywhere else; Logically, that's what one to many relationship means. It is a representation of the Observer Pattern.

一个现实世界的例子呢?

What about a real-world example?

考虑以下情况:

想象一下,您正在构建一个与播放音频有关的应用程序,某些viewController应该具有音频播放器,在最简单的情况下,我们假设它应该有一个播放/暂停按钮,而另一个按钮 - -let的说 - 以某种方式显示一个播放列表,不管它应该如何。

Imagine that you are building an application that related to playing audios, some of viewControllers should have a view of an audio player, in the simplest case, we assume that it should has a play/pause button and another button for -let's say- somehow showing a playlist, regardless of how should it looks like.

到目前为止,音频播放器视图分开了 UIView 类和 .xib 文件,它应该作为子视图添加到任何所需的viewController。

So far so good, the audio player view has its separated UIView class and .xib file, it should be added as a subview in any desired viewController.

现在,您如何为每个viewController的两个按钮添加功能?你可能会想到:简单来说,我将在视图类中添加一个 IBAction ,就是这样,首先看起来可能听起来不错,但是在重新思考之后有一点,你会认识到,如果你想要处理在控制器层敲击按钮的事件,它将不适用;要清楚,如果每个viewController应该在点击音频播放器视图中的按钮时执行不同的功能?例如:在A中点击播放列表viewController应该显示一个tableView,但是在B视图控件中点击它应该显示一个选择器。

Now, how could you add functionality to the both buttons for each viewController? you might think of: "Simply, I will add an IBAction in the view class and that's it", at the first look, it might sounds ok, but after re-thinking a little bit, you will recognize that it will not be applicable if you are trying to handle the event of tapping the button at the controller layer; To make clear, what if each viewController should does different functionality when tapping the buttons in the audio player view? for example: tapping the playlist in "A" viewController should display a tableView, but tapping it in "B" viewController should display a picker.

>授权 :

音频播放器视图

// here is the protocol for creating the delegation:
protocol AudioPlayerDelegate {
    func playPauseDidTap()
    func playlistDidTap()
}

class AudioPlayerView: UIView {
    //MARK:- IBOutlets
    @IBOutlet weak private var btnPlayPause: UIButton!
    @IBOutlet weak private var btnPlaylist: UIButton!

    // MARK:- Delegate
    var delegate:AudioPlayerDelegate?

    // IBActions
    @IBAction private func playPauseTapped(_ sender: AnyObject) {
        delegate?.playPauseDidTap()
    }

    @IBAction private func playlistTapped(_ sender: AnyObject) {
        delegate?.playlistDidTap()
    }
}

View Controller:

class ViewController: UIViewController {

}

extension ViewController: AudioPlayerDelegate {
    func playPauseDidTap() {
        print("play/pause tapped!!")
    }

    func playlistDidTap() {
        // note that is should do a different behavior in each viewController...
        print("list tapped!!")
    }
}






h2>

您还可以检查委托模式从Stack Overflow文档 - Swift语言/协议。


Also

You can also check Delegate Pattern from Stack Overflow Documentation - Swift Language/Protocols.

有关Swift中使用的设计模式的更多信息,您可能需要检查设计模式从Stack Overflow文档 - Swift语言。

For more about design patterns that used in Swift, you might want check Design Patterns from Stack Overflow Documentation - Swift Language.

这篇关于Swift 3代表的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆