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()
    }
相关推荐
枫叶丹412 分钟前
【HarmonyOS 6.0】ArkWeb PDF预览回调功能详解:让PDF加载状态可控可感
开发语言·华为·pdf·harmonyos
小陈工24 分钟前
数据库Operator开发实战:以PostgreSQL为例
开发语言·数据库·人工智能·python·安全·postgresql·开源
耿雨飞25 分钟前
Python 后端开发技术博客专栏 | 第 07 篇 元类与类的创建过程 -- Python 最深层的魔法
开发语言·python
qq_120840937126 分钟前
Three.js AnimationMixer 工程实战:骨骼动画、剪辑切换与时间缩放
开发语言·javascript·ecmascript
Dxy123931021633 分钟前
Python在图片上画多边形:从简单轮廓到复杂区域标注
开发语言·python
楼田莉子37 分钟前
同步/异步日志系统:日志器管理器模块\全局接口\性能测试
linux·服务器·开发语言·c++·后端·设计模式
人邮异步社区40 分钟前
文科生零基础学 Python 难吗?真不难,难的是找对书!
开发语言·python
春栀怡铃声1 小时前
【C++修仙录02】筑基篇:类和对象(上)
开发语言·c++·算法
悟空爬虫-彪哥1 小时前
2026 Python UI 框架选择指南:从 Streamlit 到 Pyside6 的四层体系
开发语言·python·ui
旷世奇才李先生1 小时前
Python\+ERNIE实战:字节跳动式AI内容审核完整实现(附源码)
开发语言·人工智能·python