Swift 中的委托示例 [英] Examples of Delegates in Swift

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

问题描述

我一直在努力学习如何使用协议进行委托.我什么都懂,但除了使用表格视图和可能的滚动视图之外,我想不出什么时候使用委托.

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.

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

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:

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

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 世界中使用 委托 是如此常见,我假设您可以看到许多提供委托/数据源的类,以便为使用的实例提供属性或行为.它是 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 other in iOS, you might want to know that there are:

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

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

所以,问题是:那么为什么我应该使用委托而不是那些选项?"

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

我会尽量简化;当两个对象之间存在一对一关系时,我建议使用委托.为了更清楚,目标讨论通知中心的目的是在使用委托时尝试理解:

I will try to make it simple; I would suggest the use of 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 try to make sense when delegations are used:

NotificationCenter 代表一对多关系;简单地说,它的工作原理是:发布(通知)关于特定事件的通知并观察(得到通知)这个通知——它可以在任何地方被观察到 否则;从逻辑上讲,这就是一对多关系的含义.它代表了观察者模式.

NotificationCenter represents one to many relationship; Simply, it works as: posting (notifying) a notification on a specific event and observing (get notified about) 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.

为了简化起见,我将其称为步骤:

For the purpose of simplifying, I would mention it as steps:

  1. 了解要求:每个委托都有自己的规则,列在委托协议中,这是一组方法签名您应该实施以符合此委托.

  1. Knowing the requirements: Each delegate has its own rules, listed in the delegate protocol which is a set of method signatures that you should implement for conforming this delegation.

符合委托:这只是通过标记让您的班级成为委托.例如:class ViewController: UIViewController, UITableViewDelegate {}.

Conforming for the delegation: it is simply letting your class to be a delegate, by marking it. For instance: class ViewController: UIViewController, UITableViewDelegate {}.

连接委托对象:将您的类标记为委托是还不够,您需要确保您要确认的对象您的班级为您的班级提供所需的工作.

Connecting the delegate object: Marking your class to be a delegate is not enough, you need to make sure that the object you want to be confirmed by your class to give the required job to your class.

实现要求:最后,您的类必须实现委托协议中列出的所有必需方法.

Implementing the requirements: Finally, your class have to implement all required methods listed in the delegate protocol.

<小时>

例如

听起来是不是有点混乱?一个真实世界的例子怎么样?


For Example

Does it sounds a little confusing? What about a real-world example?

考虑以下场景:

假设您正在构建一个与播放音频相关的应用程序.一些 viewController 应该有一个音频播放器的视图.在最简单的情况下,我们假设它应该有一个播放/暂停按钮和另一个按钮,比如说,以某种方式显示播放列表,无论它看起来如何.

Imagine that you are building an application related to playing audios. Some of the viewControllers should have a view of an audio player. In the simplest case, we assume that it should have a play/pause button and another button for, let's say, showing a playlist somehow, regardless of how it may look 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"viewController 中的播放列表将显示一个选择器.

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

好吧,让我们对这个问题应用委托:

Well, let's apply Delegation to this issue:

#"注释代表如何申请委托?"的步骤.部分.

音频播放器视图:

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

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

    // MARK:- Delegate
    weak var delegate: AudioPlayerDelegate?

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

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

视图控制器:

class ViewController: UIViewController {
    var audioPlayer: AudioPlayerView?

    // MARK:- Life Cycle
    override func viewDidLoad() {
        super.viewDidLoad()

        audioPlayer = AudioPlayerView()
        // # 3: the "AudioPlayerView" instance delegate will implemented by my class "ViewController"
        audioPlayer?.delegate = self
    }
}

// # 2: "ViewController" will implement "AudioPlayerDelegate":
extension ViewController: AudioPlayerDelegate {
    // # 4: "ViewController" implements "AudioPlayerDelegate" requirments:
    func playPauseDidTap() {
        print("play/pause tapped!!")
    }

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


快速提示:

使用委托的示例之一是传递视图控制器之间的数据返回.

As one of the most popular examples of using delegation is Passing Data Back between View Controllers.

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

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