Swift中的代表示例 [英] Examples of Delegates in Swift

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

问题描述

我一直在尝试学习委托协议的工作方式。我了解了所有内容,但是除了使用表视图和可能的滚动视图时,我无法想到何时使用委托。



通常,何时使用委托? / p>

解决方案

什么是委派?



首先,您应该知道委派模式并非仅适用于iOS世界:


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

但是与在iOS世界中的授权很常见,我假设您可以看到许多提供授权/数据源以提供abi的类。不愿为使用的实例提供属性或行为。这是对象如何在CocoaTouch中彼此对话的主要机制之一。






替代方法:



但是,委托不是唯一的使对象在iOS中相互交谈的方法,您可能想知道有:





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








何时使用委派?



问题是:那我为什么要使用委派而不是那些选项?



我将尝试使其变得简单;当两个对象之间具有 一对一 关系时,我建议使用委托。为了更清楚一点,在 NotificationCenter 上稍作讨论的目标是为了使使用委托时有意义:



NotificationCenter 表示 一对多 关系;简而言之,它的工作方式如下:发布(通知)关于特定事件的通知,观察(获得通知)该通知-可以在任何地方其他;从逻辑上讲,这就是一对多关系的意思。它表示观察者模式






如何申请授权?



为简化起见,我将其作为步骤提及:


  1. 了解要求:每个代表都有自己的规则,在委托协议,这是您为实现此委派而应实现的一组方法签名。


  2. 为委派而遵循:只需标记您的班级即可使其成为委托。例如: class ViewController:UIViewController,UITableViewDelegate {}


  3. 连接委托对象:仅将您的班级标记为委托是不够的,您需要确保班级希望确认的对象能够为班级提供所需的工作。


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







例如



听起来有点混乱吗?真实示例如何?



请考虑以下情形:



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



到目前为止,音频播放器视图具有独立的 UIView 类和 .xib 文件;它应该作为子视图添加到任何所需的viewController中。



现在,如何为每个viewController的两个按钮添加功能?您可能会想:简单来说,我将在视图类中添加 IBAction 就是这样,乍一看,这听起来似乎还不错,但是在重新考虑了一下之后一点,您将意识到,如果您尝试处理在控制器层上点击按钮的事件,它将不适用;为了清楚起见,如果在音频播放器视图中点击按钮时,每个viewController实现不同的功能怎么办?例如:在 A viewController中点击播放列表将显示一个tableView,但在 B viewController中点击播放列表将显示一个选择器。



好,让我们应用委派到此问题:



#注释代表如何应用委派?的步骤。



音频播放器视图:

  //#1:这是创建委托的协议
协议AudioPlayerDelegate:类{
func playPauseDidTap()
func playlistDidTap()
}

类AudioPlayerView:UIView {
// MARK:-IBOutlets
@IBOutlet弱私有var btnPlayPause:UIButton!
@IBOutlet弱私有变量btnPlaylist:UIButton!

//标记:-委托
弱变量委托:AudioPlayerDelegate?

// IBActions
@IBAction私人函数playPauseTapped(_ sender:AnyObject){
proxy?.playPauseDidTap()
}

@IBAction私人功能playlistTapped(_发件人:AnyObject){
代表?.playlistDidTap()
}
}

视图控制器:

  class ViewController:UIViewController { 
var audioPlayer:AudioPlayerView吗?

//标记:-生命周期
覆盖func viewDidLoad(){
super.viewDidLoad()

audioPlayer = AudioPlayerView()
//#3: AudioPlayerView实例委托将由我的类 ViewController实现。
audioPlayer?.delegate = self
}
}

// #2: ViewController将实现 AudioPlayerDelegate:
扩展ViewController:AudioPlayerDelegate {
// // 4: ViewController将实现 AudioPlayerDelegate要求:
func playPauseDidTap(){
print(轻按播放/暂停!)
}

func playlistDidTap(){
//注意,在每个viewController中应该执行不同的行为。 。
print( list tapped !!)
}
}



快速提示:



作为流行示例之一使用委派的方式是在视图控制器之间传递数据


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?

解决方案

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.

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.


Alternatives:

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:


When to use Delegation?

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 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.


How to Apply Delegation?

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

  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.

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

  3. 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.

  4. 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?

Consider the following scenario:

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.

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.

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:

The "#" comments represents the steps of "How to Apply Delegation?" section.

Audio Player View:

// # 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()
    }
}

View Controller:

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!!")
    }
}


Quick Tip:

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

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

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