需求:利用代理实现反响传值(以下例子采用点击第二个视图控制器中的按钮来改变第一个视图控制器中的Label的内容)
一、创建RootViewController
- importFoundation
- importUIKit
-
- classRootViewController:UIViewController,ChangeWordDelegate{
- varqzLabel:UILabel?
- overridefuncviewDidLoad(){
- super.viewDidLoad()
- self.title="RootViewController"
- letrightBtn:UIBarButtonItem=UIBarButtonItem(title:"下一页",style:.Plain,target:self,action:"nextPage")
- self.navigationItem.rightBarButtonItem=rightBtn
- letrect=CGRect(x:0,y:200,width:320,height:50)
- qzLabel=UILabel(frame:rect)
- qzLabel!.text="秦志伟"
- qzLabel!.textAlignment=NSTextAlignment.Center
- self.view.addSubview(qzLabel)
-
- }
- funcnextPage(){
- letsvc=SecondViewController()
- svc.delegate=self
- self.navigationController.pushViewController(svc,animated:true)
- }
- funcchangeWord(controller:SecondViewController,string:String){
- qzLabel!.text=string
- println("qzLabel.text==(string)")
- }
二、创建SecondViewController
- protocolChangeWordDelegate:NSObjectProtocol{
- //回调方法
- SecondViewController:UIViewController{
- vartemp=0
- delegate:ChangeWordDelegate?
- self.title="SecondViewController"
- self.view.backgroundColor=UIColor.greenColor()
- 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)
- myButton.center=CGPointMake(160,200)
- myButton.setTitle("改变Label内容",forState:.Normal)
- myButton.addTarget("btnClicked",forControlEvents:.TouchUpInside)
- self.view.addSubview(myButton)
- funcbtnClicked(){
- temp++
- println("我被点击了!")
- if(delegate){
- delegate?.changeWord("秦志伟"+String(temp))
- }
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|