swift - 在导航 Controller 中使用协议(protocol)委托(delegate)移动数据

标签 swift delegates protocols segue

我正在开发一个应用程序,我需要将数据传递给导航 Controller 并返回。
我使用本教程让它工作:link

在我的应用程序中,我从我的第一个 View Controller (在教程 uiviewcontroller 中)到 secondViewcontroller(在教程 fooTwoVC 中)的推送 segue 也拥有另一个 View Controller 。

那么我的问题是我可以为那个 VC 使用相同的协议(protocol)还是我需要制定另一个协议(protocol)?

import UIKit

class ViewController: UIViewController,FooTwoViewControllerDelegate {
    @IBOutlet var colorLabel : UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    func myVCDidFinish(controller: FooTwoViewController, text: String) {
        colorLabel.text = "The Color is " +  text
        controller.navigationController?.popViewControllerAnimated(true)
    }
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if segue.identifier == "mySegue"{
            let vc = segue.destinationViewController as! FooTwoViewController
            vc.colorString = colorLabel.text!
            vc.delegate = self
        }
    }
}
import UIKit

protocol FooTwoViewControllerDelegate{
    func myVCDidFinish(controller:FooTwoViewController,text:String)
}

class FooTwoViewController: UIViewController {
    var delegate:FooTwoViewControllerDelegate? = nil
    var colorString:String = ""
    @IBOutlet var colorLabel : UILabel!

    @IBAction func saveColor(sender : UIBarButtonItem) {
        if (delegate != nil) {
            delegate!.myVCDidFinish(self, text: colorLabel!.text!)
        }
    }

    @IBAction func colorSelectionButton(sender: UIButton) {
         colorLabel.text = sender.titleLabel!.text!
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        colorLabel.text = colorString
    }
}

最佳答案

过了一段时间我终于弄明白了,毕竟也没那么难。
我只需要将协议(protocol)更改为:

protocol FooTwoViewControllerDelegate{ 
func myVCDidFinish(controller:UIViewController,text:String)
}

所以我可以被其他 View Controller 使用。 此外,我在第三个 View Controller 中使用了相同的代码。

有什么问题随时问。

关于swift - 在导航 Controller 中使用协议(protocol)委托(delegate)移动数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35259107/

相关文章:

python - 将整个函数作为字符串获取/并将字符串转换为函数?

arrays - 使自定义类型符合仅具有下标的 RandomAccessCollection

ios - 委托(delegate)方法发送自己的对象或不发送它

swift - iOS SWIFT 应用程序 - 如何全局忽略 SIGPIPE 信号?

ios - 从 SyncTable 拉取更新核心数据对象,而不是调用 NSFeatchedResults 委托(delegate)方法

swift - 无法在 swift ("if"或可能 "while"中创建正确的函数)

clojure - 哪个协议(protocol)在 clojure 中定义了 conj?

swift - 无法将按钮操作拖动到 Xcode 8 中的现有功能

UITableView 编辑/完成事件

iphone - 协议(protocol)和委托(delegate)不能正常工作