【问题标题】:How to pass data between UITableViewCells? ...and store the passed data?如何在 UITableViewCells 之间传递数据? ...并存储传递的数据?
【发布时间】:2020-06-30 11:17:34
【问题描述】:

我想要达到的效果如上图所示:当func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 被调用时,我想在它和另一个 UITableViewController、Input VC 和 DataVC 之间传递数据。但是我被困在如何实现这一点上。

它们都有一个共享模型,允许在其基础数据更改时更新单元格。

我打算使用协调器模式在 UIViewControllers 和 不是 Segue 之间导航。


这是我想出的代码:

型号:

struct ModelForDealer {
   var dealerName: String?
}

UIViewController 中模型的实例:

let modelForDealer: [ModelForDealer] = [
   ModelForDealer(dealerName: "General Motors"),
   ModelForDealer(dealerName: "General Motors"),
   ModelForDealer(dealerName: "General Motors"),
   ModelForDealer(dealerName: "General Motors"),
   ModelForDealer(dealerName: "General Motors"),
   ModelForDealer(dealerName: "General Motors")]

和 UIViewController 中的单元类:

class CellForDealer: UITableViewCell {

   @IBOutlet weak var titleForDealer: UILabel!
               
   func configCellForDealer(with model: ModelForDealer) {
      titleForDealer?.text = model.dealerName
   }
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
   NSLog("Cell is tapped")
   switch indexPath.row {
   case 0:
    self.coordinator?.gotoDetailDataView()
   default:
     self.coordinator?.gotoDetailDataView()
     break
   }
}

【问题讨论】:

  • 提供你试过的代码
  • 添加你目前尝试过的代码。
  • 您要在DetailVC 中进行更改并反映在InputVC 中吗?
  • @PGDev,不,我希望更改反映在 InputVC 中,我点击 InputVC 内的单元格,将我带到 DetailVC,我点击 DetailVC 内的单元格,更改会反映回来在 InputVC 中。那可能吗..?然后怎么样,我被卡住了..
  • @PGDev,我更新了问题详情,你能看看吗?

标签: ios swift uitableview generics


【解决方案1】:

这里是你可以继续的方法,

1. 在您的 DetailVC 中创建一个处理程序并在 didSelectRowAt 上调用它并在其中传递相关数据

class DetailVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
    var handler: ((String)->())?
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let value = "Red Color" //get your data here that you want to pass back
        handler?(value)
    }
    
    //rest of the code...
}

2. 然后在 InputVC 中创建 DetailVC 的实例时设置处理程序,即..

class InputVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
    //rest of the code...
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.openDetailVC(model: modelForDealer[indexPath.row])
    }
    
    func openDetailVC(model: ModelForDealer) {
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "DetailVC") as! DetailVC
        vc.handler = {(str) in //here....
            print(str)
        }
        //rest of the code...
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

【讨论】:

  • 我得到线程 1:信号 SIGABRT 错误,它显示“无法将 InputVC 类型的值转换为 DetailVC”
猜你喜欢
  • 1970-01-01
  • 2021-10-10
  • 2014-05-22
  • 2011-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-27
  • 2011-07-08
相关资源
最近更新 更多