You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift无Storyboard:UICollectionViewCell间文本框数据传递问题

搞定UICollectionViewCell间的文本传递问题

我来帮你梳理下怎么实现这个需求——把Cell1里UITextField的内容,传递到ViewController2对应的Cell2文本框里。你现有代码的核心问题是代理协议没带数据参数,咱们一步步改:

1. 给代理协议加上数据传递参数

首先修改InfoCellDelegate,让它的方法能接收要传递的文本:

protocol InfoCellDelegate: class {
    // 新增text参数用来传递内容
    func buttonToDetailCell(withText text: String)
}

2. 在Cell1里调用代理时传入文本

修改Cell1的按钮点击方法,把UITextField的内容作为参数传给代理(顺便调整下命名,符合Swift小驼峰规范):

// UICollectionViewCell 1代码
weak var delegate: InfoCellDelegate?

@objc func infoButtonPressed(_ sender: UIButton) {
    // 安全获取文本,为空就不跳转
    guard let inputText = cellOne.text, !inputText.isEmpty else {
        return
    }
    // 调用代理方法时传入文本
    delegate?.buttonToDetailCell(withText: inputText)
}

3. 在ViewController1中把数据传给ViewController2

首先给目标控制器InfoViewController加个属性,用来存传递过来的文本:

// InfoViewController(也就是你的ViewController2)代码
var receivedText: String?

然后修正ViewController1里的代理实现——你原来写成class func是错的,代理方法必须是实例方法,改成这样:

// ViewController1的扩展实现代理
extension ViewController1: InfoCellDelegate {
    func buttonToDetailCell(withText text: String) {
        let layout = UICollectionViewFlowLayout()
        let vc = InfoViewController(collectionViewLayout: layout)
        // 把文本赋值给目标控制器的属性
        vc.receivedText = text
        navigationController?.pushViewController(vc, animated: true)
    }
}

4. 在ViewController2里给Cell2设置文本

最后,在ViewController2配置Cell2的时候,把收到的文本设置到对应的UITextField里:

// ViewController2的UICollectionView数据源方法
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "你的Cell2复用ID", for: indexPath) as! 你的Cell2类名
    // 把传递过来的文本赋值给Cell2的UITextField
    cell.cell2TextField.text = receivedText
    return cell
}

这样改完之后,点击Cell1的按钮,文本就能顺利传到ViewController2的Cell2文本框里啦~

内容的提问来源于stack exchange,提问作者panthro1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:47:36