在Swift中传递数据 [英] Passing Data in Swift

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

问题描述

我一直在寻找答案,但只找到了segues的答案。

I have been looking for an answer for this, but have only found answers for segues.

我有一个 viewController1 ,其中一个按钮可以转换为 viewController2 。没有代码,我通过Interface builder进行设置。在 viewController2 我有一个按钮,用

I have viewController1 with a button that segues to viewController2. There is no code for this, I set it up through Interface builder. On viewController2 I have a button that dismisses itself with

 self.dismissViewControllerAnimated(true, completion, nil)

我想从 viewController2传递一个字符串当视图被解除时返回 viewController1 。我该怎么做呢?另外,我正在使用swift。

I want to pass a string from viewController2 back to viewController1 when the view is dismissed. How do I go about doing this? Also, I am using swift.

提前致谢!

推荐答案

有两种常见的模式,这两种模式都不需要viewController2明确地了解viewController1(这对于可维护性来说非常好):

There are two common patterns, both of which eliminate the need for viewController2 to know explicitly about viewController1 (which is great for maintainability):


  1. 为viewController2创建委托协议,并将viewController1设置为委托。每当你想将数据发送回viewController1时,让viewController2发送委托数据

  1. Create a delegate protocol for your for viewController2 and set viewController1 as the delegate. Whenever you want to send data back to viewController1, have viewController2 send the "delegate" the data

将闭包设置为允许传递数据的属性。 viewController1在显示viewController2时会在viewController2上实现该闭包。每当viewController2有要传回的数据时,它就会调用闭包。我觉得这种方法更快捷。

Setup a closure as a property that allows passing the data. viewController1 would implement that closure on viewController2 when displaying viewController2. Whenever viewController2 has data to pass back, it would call the closure. I feel that this method is more "swift" like.

以下是#2的一些示例代码:

Here is some example code for #2:

class ViewController2 : UIViewController {
    var onDataAvailable : ((data: String) -> ())?

    func sendData(data: String) {
        // Whenever you want to send data back to viewController1, check
        // if the closure is implemented and then call it if it is
        self.onDataAvailable?(data: data)
    }
}

class ViewController1 : UIViewController {
   func doSomethingWithData(data: String) {
        // Do something with data
    }
    override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
        // When preparing for the segue, have viewController1 provide a closure for
        // onDataAvailable
        if let viewController = segue.destinationViewController as? ViewController2 {
            viewController.onDataAvailable = {[weak self]
                (data) in
                if let weakSelf = self {
                    weakSelf.doSomethingWithData(data)
                }
            }
        }
    }
}

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

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