您的位置:首页 > 其它

使用协议Protocol实现ViewController之间传值

2015-12-17 13:50 239 查看
1、定义协议Protocol 名为PassValue

//定义一个协议
protocol PassValue {

func passValue(value:String)
}

2、定义两个ViewController , 名为 ViewController1 和 ViewController2 。

3、实现ViewController1到ViewController2正向传值,并在本页实现协议设置delegate

class ViewController1:
UIViewController,PassValue{

override func viewDidLoad() {

super.viewDidLoad()

self.navigationItem.title =
"ViewController"

self.navigationItem.rightBarButtonItem =
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target:
self, action:
"pushVc")
}

func pushVc(){

var vc2 = ViewController2()
vc2.name =
"Vc1 Value"
vc2.delegate =
self //设置代理方法

self.navigationController?.pushViewController(vc2, animated:
true)
}

//委托的方法

func passValue(value:String){

//将返回的数据显示在label控件上

var label2 = UILabel(frame:
CGRect(x: 10, y:
80, width: 120, height:
40))
label2.text = value

self.view.addSubview(label2)
}
}

4、实现ViewController2到ViewController1反向传值

class ViewController2:
UIViewController {

var name = ""

var delegate:PassValue?

override func viewDidLoad() {

super.viewDidLoad()

self.navigationItem.title =
"ViewController2"

self.navigationItem.leftBarButtonItem =
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target:
self, action:
"popVc")

var label1 = UILabel(frame:
CGRect(x: 10, y:
80, width: 130, height:
40))
label1.text =
name

self.view.addSubview(label1)

}

func popVc(){

delegate?.passValue(" My Return ") //协议中的方法

self.navigationController?.popViewControllerAnimated(true)
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: