Swift 协议(Protocol)和代理(Delegate)回调

作用:从次页传值到首页

次页只修改数据,而数据的展示(更新UI)则交由首页完成

首页:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, EditViewControllerDelegate {

    @IBOutlet var myTableView: UITableView!

    fileprivate var selectIndexPath: IndexPath?
    fileprivate var dataSource:Array<Dictionary<String, String>>?
    
    //life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        self.myTableView.dataSource = self
        self.myTableView.delegate = self
        self.createSourceData()
    }
    
    //Table要显示的数据
    func createSourceData() {
        ... ...
    }
    
    // 实现 EditViewControllerDelegate    
    func fetchGirlName(_ name: String) {
        
        if selectIndexPath != nil {
            //获取当前点击Cell的索引
            let index = ((selectIndexPath as NSIndexPath?)?.row)!
            
            //更新数据源中相应的数据
            self.dataSource![index][GIRL_NAME] = name
            
            //重载TableView
            self.myTableView.reloadData()
        }        
    }    
    
    //UITableViewDelegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        //记录当前点击的IndexPath
        self.selectIndexPath = indexPath
        
        //获取当前点击的Cell对象
        let currentSelectCell:BeautifulGrillCell? = self.myTableView.cellForRow(at: indexPath) as? BeautifulGrillCell
        
        //从storyboard中实例化编辑视图控制器
        let editViewController:EditViewController = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "EditViewController") as! EditViewController
        
        //指定编辑视图控制器委托代理对象
        editViewController.delegate = self
        
        //把点击Cell上的值传递给编辑视图控制器
        if currentSelectCell != nil {
           editViewController.girlOldName = currentSelectCell!.girlNameLable.text!
        }
        
        //push到编辑视图控制器
        self.navigationController?.pushViewController(editViewController, animated: true)
    }
...
...

自定义TableViewCell:
...
...

次页:

import UIKit

protocol EditViewControllerDelegate: NSObjectProtocol{
    func fetchGirlName(_ name:String)
}

class EditViewController: UIViewController {
    
    var girlOldName:String?
    weak var delegate: EditViewControllerDelegate?
    @IBOutlet var girlNameTextField: UITextField!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if self.girlOldName != nil {
            self.girlNameTextField.text = self.girlOldName!
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        let name:String! = self.girlNameTextField.text
        if  name != "" {
            if delegate != nil {
                delegate!.fetchGirlName(name)
            }
        }
    }
    ...
    ...
}

Comments are closed.