swift基础学习传值[属性传值、代理、block代码块、等]
传值:在此之前我们先定义两个视图控制器ViewController ViewController01 1.属性传值正向、这里以字符串做例子、其他类型类似:ViewController->>>ViewController01 ViewController: let vc = ViewController01() vc.str ="hello" self.navigationController?.pushViewController(vc,animated:true) ViewController01: class ViewController01: UIViewController { var str =NSString() overridefunc viewDidLoad() { super.viewDidLoad() self.view.backgroundColor =UIColor.white print(self.str) } overridefunc didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } 2.代码块反向传值 ViewController: func click() { let vc =ViewController01() vc.callBlock{(value: String?) ->Void in print(value) } self.navigationController?.pushViewController(vc,animated:true) } ViewController01: 首先定义代码块类型:typealias textBlock = (String)->() 然后定义代码块属性:var block:textBlock? 实现代码块 func callBlock(block:textBlock?) { self.block = block } func click() {
if let block = self.block { block("li01") } self.navigationController?.popToRootViewController(animated:true) } 3.delegate反向传值(协议) ViewController:首先要继承ViewController01中的协议giveFirstStrDelegate func click() { let vc =ViewController01() vc.delegate = self self.navigationController?.pushViewController(vc,animated:true) } 代理方法 func giveStr(controller: ViewController01,string: String) { print(string) } ViewController01: 首先定义个协议 protocol giveFirstStrDelegate:NSObjectProtocol { func giveStr(controller:ViewController01,string:String) } var delegate:giveFirstStrDelegate? 这些类似与OC中的代理实现 func click() { if((delegate) !=nil){ delegate?.giveStr(controller:self,string:"hi I am li") }
self.navigationController?.popToRootViewController(animated:true) } 4.通知中心传值参考OC 5.单列传值也同样参考OC 基本是写过OC的swift都可以很容易上手 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |