iOS开发Swift-反向传值

反向传值是指将后续页面(2)得到的值传回首页(1).

1.在2页面代码中写protocol.

复制代码
protocol TodoTableViewControllerDelegate{
    func didAdd(name: String)
    func didEdit(name: String)
}

制定了一个名为TodoTableViewControllerDelegate的协议,在其中写了一个didEdit方法,传值内容是一个String.

2.在1页面代码中实现这个方法.

复制代码
extension TodosViewController: TodoTableViewControllerDelegate{
    func didAdd(name: String){
        todos.append(Todo(name: name, checked: false))
        tableView.insertRows(at: [IndexPath(row: todos.count - 1, section: 0)], with: .automatic)
        
    }
    func didEdit(name: String) {
        //待实现
    }
}

在扩展类TodosViewController中实现TodoTableViewControllerDelegate协议,在里边实现方法didEdit.

3.完成点击按钮之后的逻辑

复制代码
    @IBAction func done(_ sender: Any) {
        
        if !todoTextView.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty{
            
            //如果name不等于nil则编辑待办事项
            if name != nil{
                delegate?.didEdit(name: todoTextView.text)
            }else{
                //如果name为nil时说明用户在新增待办事项
                delegate?.didAdd(name: todoTextView.text)
            }
            
        }
        
        navigationController?.popViewController(animated: true)
    }

这样的话todoTextView的text值就传到了delegate中.再去实现didEdit.

4.完成1中prepare逻辑.当进入编辑界面时需要正向传值.

复制代码
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as! TodoTableViewController
        vc.delegate = self
        if segue.identifier == kEditTodoID{
            //正向传值
            let cell = sender as! TodoCell
            vc.delegate = self
            //通过cell找indexPath
            row = tableView.indexPath(for: cell)?.row
            vc.name = todos[row!].name
        }
    }

5.传值成功后刷新界面以呈现编辑成功后的内容.

复制代码
    func didEdit(name: String) {
        todos[row].name = name
        
//        let indexPath = IndexPath(row: row, section: 0)
//        let cell = tableView.cellForRow(at: indexPath) as! TodoCell
//        cell.todoLable.text = todos[row].name
        tableView.reloadData()
    }
相关推荐
步、步、为营3 分钟前
.NET 事件模式举例介绍
java·开发语言·.net
~plus~6 分钟前
WPF八大法则:告别模态窗口卡顿
开发语言·经验分享·后端·程序人生·c#
march of Time17 分钟前
go工具库:hertz api框架 hertz client的使用
开发语言·golang·iphone
24K纯学渣38 分钟前
Python编码格式化之PEP8编码规范
开发语言·ide·python·pycharm
怒视天下40 分钟前
零基础玩转Python生物信息学:数据分析与算法实现
开发语言·python
GISer_Jing1 小时前
Three.js中AR实现详解并详细介绍基于图像标记模式AR生成的详细步骤
开发语言·javascript·ar
委婉待续1 小时前
Qt的学习(一)
开发语言·qt·学习
笨笨马甲1 小时前
Qt Quick Layout功能及架构
开发语言·qt
Dovis(誓平步青云)1 小时前
探索C++标准模板库(STL):String接口的底层实现(下篇)
开发语言·c++·stl·string
海棠一号2 小时前
JAVA理论第五章-JVM
java·开发语言·jvm