swift代理的使用,和oc版本有区别,区别还是蛮大的,不过和oc一样都是用于反向传值:
实现如下:
1,声明两个类
2,实现流程,viewcontroller页面点击按钮进入firstVC页面,然后在firstVC页面修改值,返回把值传到viewcontroller页面
3,具体实现:
a 在firstVC页面声明代理
import UIKit class FirstViewController: UIViewController { @IBOutlet weak var textField: UITextField! var delegate:EditViewControllerDelegate? var oldStr:String? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if oldStr != nil { textField.text = oldStr } } @IBAction func sendAction(_ sender: Any) { delegate?.edidStr(controller: self, newInfo: textField.text!) } @IBAction func disMissAction(_ sender: Any) { delegate?.editStrDidCancel(controller: self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }
b 声明代理方法
protocol EditViewControllerDelegate {
func edidStr(controller:FirstViewController,newInfo:String)
func editStrDidCancel(controller:FirstViewController)
}
c 代理方法的使用
import UIKit class ViewController: UIViewController,EditViewControllerDelegate { @IBOutlet weak var label: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } //页面跳转时 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "EditView"{ let controller = segue.destination as! FirstViewController //设置代理 controller.delegate = self //将值传递给新页面 controller.oldStr = label.text } } func edidStr(controller: FirstViewController, newInfo: String) { label.text = newInfo; controller.presentingViewController?.dismiss(animated: true, completion: nil) } func editStrDidCancel(controller: FirstViewController) { controller.presentingViewController?.dismiss(animated: true, completion: nil) }
segue的设置:
请发表评论