需求:利用代理实现反响传值(以下例子采用点击第二个视图控制器中的按钮来改变第一个视图控制器中的Label的内容)
一、创建RootViewController
import Foundation
import UIKit
class RootViewController:UIViewController,ChangeWordDelegate{
var qzLabel:UILabel?
override func viewDidLoad(){
super.viewDidLoad()
self.title = "RootViewController"
let rightBtn:UIBarButtonItem = UIBarButtonItem(title:"下一页",style:.Plain,target:self,action:"nextPage")
self.navigationItem.rightBarButtonItem = rightBtn
let rect = CGRect(x:0,y:200,width:320,height:50)
qzLabel = UILabel(frame:rect)
qzLabel!.text = "秦志伟"
qzLabel!.textAlignment = NSTextAlignment.Center
self.view.addSubview(qzLabel)
}
func nextPage(){
let svc = SecondViewController()
svc.delegate = self
self.navigationController.pushViewController(svc,animated:true)
}
func changeWord(controller:SecondViewController,string:String){
qzLabel!.text = string
println("qzLabel.text == \(string)")
}
}
二、创建SecondViewController
import Foundation
import UIKit
//定义协议改变Label内容
protocol ChangeWordDelegate:NSObjectProtocol{
//回调方法
func changeWord(controller:SecondViewController,string:String)
}
class SecondViewController:UIViewController{
var temp = 0
var delegate:ChangeWordDelegate?
override func viewDidLoad(){
super.viewDidLoad()
self.title = "SecondViewController"
self.view.backgroundColor = UIColor.greenColor()
let rect = CGRect(x:50,y:200,width:150,height:50)
var myButton = UIButton(frame:rect)
myButton.center = CGPointMake(160,200)
myButton.setTitle("改变Label内容",forState:.Normal)
myButton.addTarget(self,action:"btnClicked",forControlEvents:.TouchUpInside)
self.view.addSubview(myButton)
}
func btnClicked(){
temp++
println("我被点击了!")
if(delegate){
delegate?.changeWord(self,string:"秦志伟"+String(temp))
}
}
}