{"id":18016004,"url":"https://github.com/linusling/differentwaystopassvalueswift","last_synced_at":"2025-03-26T18:31:37.696Z","repository":{"id":86450890,"uuid":"41711890","full_name":"LinusLing/DifferentWaysToPassValueSwift","owner":"LinusLing","description":null,"archived":false,"fork":false,"pushed_at":"2015-09-30T01:55:57.000Z","size":2668,"stargazers_count":7,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-22T06:41:42.696Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/LinusLing.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-09-01T02:19:29.000Z","updated_at":"2024-03-04T04:09:48.000Z","dependencies_parsed_at":"2023-03-05T01:26:10.351Z","dependency_job_id":null,"html_url":"https://github.com/LinusLing/DifferentWaysToPassValueSwift","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LinusLing%2FDifferentWaysToPassValueSwift","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LinusLing%2FDifferentWaysToPassValueSwift/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LinusLing%2FDifferentWaysToPassValueSwift/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LinusLing%2FDifferentWaysToPassValueSwift/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/LinusLing","download_url":"https://codeload.github.com/LinusLing/DifferentWaysToPassValueSwift/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245712766,"owners_count":20660291,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-30T04:15:48.546Z","updated_at":"2025-03-26T18:31:37.371Z","avatar_url":"https://github.com/LinusLing.png","language":"Swift","funding_links":[],"categories":[],"sub_categories":[],"readme":"# DifferentWaysToPassValueSwift\n\n这是一个工程，展示了如何在 VC 之间进行传值，包括正向传值、反向传值和无向传值。\n\n* 本示例代码基于 Xcode 7 ，并使用Swift 2.0 写成。\n\n## Demo\n\n![](https://raw.githubusercontent.com/kevin833752/DifferentWaysToPassValueSwift/master/DifferentWaysToPassValueSwift/demo.gif)\n\n## 正向传值\n\nRootVC:\n\n```swift\nlet del:DelegateViewController = DelegateViewController()\ndel.positiveValue = title! // 正向传值\nself.presentViewController(del, animated: true, completion: nil)\n```\n\nDelegateVC:\n\n```swift\nvar positiveValue:String = String() // 正向传值，接收方\n```\n\n## 反向传值\n\n反向传值包括 delegate 、闭包、KVO 和 Notification 四种种方式：\n\n### Delegate\n\nRootVC:\n\n```swift\n@IBAction func delegateButtonDidTapped(sender: AnyObject) {\n    ...\n    del.delegate = self // 设置下一个VC的delegate为当前的rootVC\n    ...\n}\n```\n\n```swift\n//实现delegate的方法\nfunc passValue(str:String) {\n    self.delegateTF.text = str\n}\n```\n\nDelegateVC:\n\n```swift\nvar delegate:delegateOfNegative? //定义具体的delegate\n```\n\n```swift\nfunc back(sender:UIButton) {\n    let tf:UITextField = self.view.viewWithTag(10000) as! UITextField\n    delegate?.passValue(tf.text!) // 调用delegate的传值方法passValue\n    self.dismissViewControllerAnimated(true, completion: nil)\n}\n```\n\n### 闭包\n\nRootVC:\n\n```swift\n@IBAction func blockButtonDidTapped(sender: AnyObject) {\n    ...\n    let blo:BlockViewController = BlockViewController()\n    // 设置block中要传递的值的接收方式\n    blo.passBlockValue = {\n        (title:String) in\n        self.positiveTF.text = title\n    }\n    self.presentViewController(blo, animated: true, completion: nil)\n}\n```\n\nBlockVC:\n\n```swift\nvar passBlockValue:((title:String) -\u003e Void)? // 定义block，包含参数title\n```\n\n```swift\nfunc back(sender:UIButton) {\n    let tf:UITextField = self.view.viewWithTag(10001) as! UITextField\n    passBlockValue?(title:tf.text!) // 使用block传递title这个值\n    self.dismissViewControllerAnimated(true, completion: nil)\n}\n```\n\n### KVO\n\nKVO只要是监听的属性，不管是正向还是反向都会触发`observeValueForKeyPath`方法，在其中做相应的显示即可。\n\nRootVC:\n\n```swift\nvar kvc:KVOViewController = KVOViewController() // 全局的KVOvc方便在deinit时removeobserver\n```\n\n```swift\n@IBAction func KVOButtonDidTapped(sender: AnyObject) {\n    kvc.k = kvo()\n        \n    // addObserver添加监听\n    kvc.k.addObserver(self, forKeyPath: \"title\", options: [NSKeyValueObservingOptions.Old, NSKeyValueObservingOptions.New], context: nil)\n    kvc.k.title = self.positiveTF.text!\n    self.presentViewController(kvc, animated: true, completion: nil)\n}\n```\n\n```swift\n// 监听对象的属性或者实例变量发生变化，就自动调用该函数，执行相应操作\noverride func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer\u003cVoid\u003e) {\n    if keyPath == \"title\" {\n        print(change!)\n        var nv = change!\n        let newvalue: AnyObject? = nv[\"new\"]\n        print(\"the new value is \\(newvalue!)\")\n        self.positiveTF.text = \"\\(newvalue!)\" // 将监听到的变化值赋值给TF来显示\n    }\n}\n\ndeinit {\n    // removeObserver移除监听\n    // add和remove必须对应，否则报错\n    kvc.k.removeObserver(self, forKeyPath: \"title\", context: nil)\n}\n```\n\nKVOVC:\n\n```swift\n//要监听的对象的定义\nclass kvo: NSObject {\n    var ptitle : String = \"\"\n    \n    // dynamic修饰的即为可支持KVO\n    dynamic var title : String {\n        get {\n            return self.ptitle\n        }\n        set {\n            self.ptitle = newValue\n        }\n    }\n    \n    override init() {\n        println(\"init\")\n    }\n    \n    deinit {\n        println(\"deinit\")\n    }\n}\n```\n\n```swift\nfunc back(sender:UIButton) {\n    let tit = (self.view.viewWithTag(10003) as! UITextField).text\n\n    k.title = tit! // 对监听的属性赋值会触发observeValueForKeyPath方法\n\n    self.dismissViewControllerAnimated(true, completion: nil)\n}\n```\n\n### Notification\n\nRootVC:\n\nviewDidLoad:\n\n```swift\n// 注册一个通知\nNSNotificationCenter.defaultCenter().addObserver(self, selector: \"notifReceive:\", name: \"notifName\", object: nil)\n```\n\n```swift\n@IBAction func NotificationButtonDidTapped(sender: AnyObject) {\n    let noti:NotificationViewController = NotificationViewController()\n    noti.positiveValue = self.positiveTF.text!\n        \n    self.presentViewController(noti, animated: true, completion: nil)    \n}\n\n// 每次调用对应name的postNotificationName方法会由selector处理\nfunc notifReceive(notification:NSNotification) {\n    self.positiveTF.text = \"\\(notification.object!)\"\n    print(\"notif : \\(notification.name), \\(notification.object!)\")\n}\n\ndeinit {\n    ...\n    // removeObserver移除对应name的通知\n    NSNotificationCenter.defaultCenter().removeObserver(self, name: \"notifName\", object: nil)\n}\n```\n\nNotificationVC:\n\n```swift\nfunc back(sender:UIButton) {\n    let tit = (self.view.viewWithTag(10004) as! UITextField).text\n        \n    // 发送一个通知，name要对应。单一数据可用object传，多个数据可以用dictionary放进userInfo传\n    NSNotificationCenter.defaultCenter().postNotificationName(\"notifName\", object: tit, userInfo: nil)\n    \n    self.dismissViewControllerAnimated(true, completion: nil)\n}\n```\n\n## 无向传值\n\n其实就是利用`NSUserDefaults`来存取数据，哈哈。\n\n## PS\n\n* 所谓“反向传值”只是在业务逻辑上是从第二个 VC 回到第一个 VC 的过程中传值。并不是说列出的几种传值方式只能在反向情况下使用。\n\n* 特别感谢 [@靛青K](http://weibo.com/2314535081) 给我提出的宝贵意见或建议 :]","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flinusling%2Fdifferentwaystopassvalueswift","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flinusling%2Fdifferentwaystopassvalueswift","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flinusling%2Fdifferentwaystopassvalueswift/lists"}