swift 协议传值的实现

时间:2022-12-06 01:03:13

首先呢说下结构

一个ViewController

一个ModelViewController

在ModelViewController中定义了一个协议

这个逻辑 从第一个界面进入第二个界面  从第二个界面回到第二个界面并通过协议传值回到第一个界面 打印输出值

ModelViewController.swift

protocol lwkDelegate {//定义协议

func changeString(newString:String)

}

在这个ModelViewControler类中实现一些简单的逻辑

class ModelViewController: UIViewController{

var delegate:lwkDelegate?

var btn:UIButton?

override func viewDidLoad() {

super.viewDidLoad()

btn=UIButton(frame:CGRectMake(110,80,100,20))

btn!.backgroundColor=UIColor.grayColor()

btn!.setTitle("传值回第一个界面",forState:.Normal)

//绑定事件

btn!.addTarget(self,action:#selector(ModelViewController.btnOnClick),forControlEvents: UIControlEvents.TouchUpInside)

self.view.addSubview(btn!)

}

func btnOnClick(){

let str:String = "liuweikai"

delegate!.changeString(str)//调用协议方法

self.dismissViewControllerAnimated(true, completion: nil)

}

在ViewController类中

class ViewController: UIViewController,lwkDelegate{//接受协议

var btn:UIButton?

override func viewDidLoad() {

super.viewDidLoad()

// Do any additional setup after loading the view, typically from a nib.

btn=UIButton(frame:CGRectMake(110,80,100,20))

btn!.backgroundColor=UIColor.greenColor()

btn!.setTitle("去二个界面",forState:.Normal)

//绑定事件

btn!.addTarget(self,action:#selector(ViewController.btnOnClick),forControlEvents: UIControlEvents.TouchUpInside)

self.view.addSubview(btn!)

}

func btnOnClick(){

let vc = ModelViewController()

vc.delegate = self //委托方

self.presentViewController(vc, animated: true, completion: nil)

//        self.navigationController?.pushViewController(vc, animated: true)

}

func changeString(newString:String) {//实现协议的方法

print(newString)

}