微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift语言实现代理传值

需求:利用代理实现反响传值(以下例子采用点击第二个视图控制器中的按钮来改变第一个视图控制器中的Label的内容

一、创建RootViewController

[objc] view plain copy
  1. importFoundation
  2. importUIKit
  3. classRootViewController:UIViewController,ChangeWordDelegate{
  4. varqzLabel:UILabel?
  5. overridefuncviewDidLoad(){
  6. super.viewDidLoad()
  7. self.title="RootViewController"
  8. letrightBtn:UIBarButtonItem=UIBarButtonItem(title:"下一页",style:.Plain,target:self,action:"nextPage")
  9. self.navigationItem.rightBarButtonItem=rightBtn
  10. letrect=CGRect(x:0,y:200,width:320,height:50)
  11. qzLabel=UILabel(frame:rect)
  12. qzLabel!.text="秦志伟"
  13. qzLabel!.textAlignment=NSTextAlignment.Center
  14. self.view.addSubview(qzLabel)
  15. }
  16. funcnextPage(){
  17. letsvc=SecondViewController()
  18. svc.delegate=self
  19. self.navigationController.pushViewController(svc,animated:true)
  20. }
  21. funcchangeWord(controller:SecondViewController,string:String){
  22. qzLabel!.text=string
  23. println("qzLabel.text==\(string)")
  24. }


二、创建SecondViewController

    //定义协议改变Label内容
  1. protocolChangeWordDelegate:NSObjectProtocol{
  2. //回调方法
  3. SecondViewController:UIViewController{
  4. vartemp=0
  5. delegate:ChangeWordDelegate?
  6. self.title="SecondViewController"
  7. self.view.backgroundColor=UIColor.greenColor()
  8. letrect=CGRect(x:50,width:150,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> varmyButton=UIButton(frame:rect)
  9. myButton.center=CGPointMake(160,200)
  10. myButton.setTitle("改变Label内容",forState:.normal)
  11. myButton.addTarget("btnClicked",forControlEvents:.TouchUpInside)
  12. self.view.addSubview(myButton)
  13. funcbtnClicked(){
  14. temp++
  15. println("我被点击了!")
  16. if(delegate){
  17. delegate?.changeWord("秦志伟"+String(temp))
  18. }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐