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()
    }
相关推荐
sali-tec11 小时前
C# 基于halcon的视觉工作流-章65 点云匹配-基于形状
开发语言·人工智能·算法·计算机视觉·c#
不会c嘎嘎11 小时前
【C++】深入理解多态:从用法到原理
开发语言·c++
Haha_bj11 小时前
iOS深入理解事件传递及响应
前端·ios·app
武子康11 小时前
Java-179 FastDFS 高并发优化思路:max_connections、线程、目录与同步
java·开发语言·nginx·性能优化·系统架构·fastdfs·fdfs
缺点内向11 小时前
如何在C#中为文本内容添加行号?
开发语言·c#·word·.net
h***85611 小时前
Rust在Web中的前端开发
开发语言·前端·rust
Chasing Aurora11 小时前
Python连接云端Linux服务器进行远程 (后端开发/深度学习)时候的注意事项
linux·开发语言·python·ubuntu·ai编程
key0611 小时前
从数据安全体系逆推数据自由度的权力本质
java·开发语言
C++ 老炮儿的技术栈11 小时前
用密码学安全随机数生成256位密钥
c语言·开发语言·c++·windows·安全·密码学·visual studio
z***438411 小时前
java与mysql连接 使用mysql-connector-java连接msql
java·开发语言·mysql