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()
    }
相关推荐
张飞签名上架几秒前
深度解析超级签:iOS 应用分发的便捷之选与风险权衡
ios·苹果签名·企业签名·苹果超级签名·tf签
superman超哥2 分钟前
Rust Rc与Arc的引用计数机制:共享所有权的两种实现
开发语言·后端·rust·编程语言·rust rc与arc·引用计数机制·共享所有权
提笔忘字的帝国3 分钟前
【2026版】macOS 使用 Homebrew 快速安装 Java 21 教程
java·开发语言·macos
半壶清水3 分钟前
【开源免费】使用 Python + Whisper + PyDub 自动切割长音频文件
开发语言·python·语言模型·开源·whisper
ghostwritten4 分钟前
go.mod 与go.sum有什么区别?
开发语言·后端·golang
2501_915918416 分钟前
iOS App的tcp、udp数据包抓取在实际开发中的使用方式
android·tcp/ip·ios·小程序·udp·uni-app·iphone
抹香鲸之海9 分钟前
Easyexcel 多级横向合并表头
java·开发语言·windows
superman超哥10 分钟前
Rust 生命周期子类型:类型系统中的偏序关系
开发语言·后端·rust·编程语言·rust生命周期·偏序关系
雒珣11 分钟前
qt界面和图片疯狂变大的bug问题
开发语言·qt·bug
BD_Marathon13 分钟前
SpringMVC——bean加载控制
java·开发语言·数据库