本文介绍了在 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 中传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 07:20