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()
    }
相关推荐
潜创微科技--高清音视频芯片方案开发2 小时前
2026年C转DP芯片方案深度分析:从适配场景到成本性能的优选指南
c语言·开发语言
Thomas.Sir2 小时前
第三章:Python3 之 字符串
开发语言·python·字符串·string
刘景贤2 小时前
C/C++开发环境
开发语言·c++
Dxy12393102163 小时前
Python 根据列表中某字段排序:从基础到进阶
开发语言·windows·python
competes3 小时前
学生需求 交易累计积分,积分兑换奖品
java·大数据·开发语言·人工智能·java-ee
splage4 小时前
Java进阶——IO 流
java·开发语言·python
青桔柠薯片4 小时前
从C语言到裸机运行:i.MX6ULL 的 GPIO 控制与编译链接过程分析
c语言·开发语言·imx6ull
OasisPioneer4 小时前
现代 C++ 全栈教程 - Modern-CPP-Full-Stack-Tutorial
开发语言·c++·开源·github
weixin_537590454 小时前
《C程序设计语言》练习答案(练习1-13)
c语言·开发语言·c#