快速获取另一个 ViewController 中选定单元格的数据(以编程方式)

MLy*_*yck 0 uitableview tableviewcell ios swift

这个问题已经回答过很多次了。但是我能找到的答案对我不起作用,因为我似乎无法调用单元格的类。

进一步解释:

我有一个带有 UITable 的 viewController。单元格在 UITableViewCell 类中配置。(我需要从这个类中提取信息)

我的“细胞类”被称为 mySuggestionsCel

这是我的“didSelectRowAtIndexPath”代码

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.allowsSelection = false

    var selectedCell:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!

    var VC = detaiLSuggestion_VC()
    self.navigationController?.pushViewController(VC, animated: true)


    if selectedCell.backgroundColor == UIColor.formulaFormColor() {
        selectedCell.backgroundColor = UIColor.formulaMediumBlue()
        UIView.animateWithDuration(0.5, animations: {
            selectedCell.backgroundColor = UIColor.formulaFormColor()
        })
    } else {
        selectedCell.backgroundColor = UIColor.formulaGreenColor()
        UIView.animateWithDuration(0.5, animations: {
            selectedCell.backgroundColor = UIColor.formulaLightGreenColor()
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

我试着做

mySuggestionsCell.someVariable

我也试过 selectedCell.someVariable

都没有工作。

我需要从我的单元格类中的 detailSuggestion_VC() 中获取此信息。但是它需要提取的数据是被选中的特定单元格的数据。这就是为什么我在让它工作时遇到了一些麻烦。

我环顾了一会。但是找不到这个特定问题的任何问题或答案。

任何帮助将不胜感激

Kel*_*Lau 5

我做出以下假设:

  1. 您有一个 tableViewCell 类文件来控制您的表格单元格。
  2. 您有一个详细视图控制器,当您点击单元格时,您的表格会转到该控制器。

  3. 您想要做的是传递点击单元格的信息,以便您的新视图控制器拥有单元格的所有信息。

取而代之的是: var selectedCell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!

您将需要对 tableViewCell 类进行类型转换。像这样:

var selectedCell = tableView.cellForRowAtIndexPath(indexPath)! as tableViewCell

接下来需要做的是调用以下函数:

performSegueWithIdentifier(/*Segue Identifier goes here*/, sender: selectedCell)

进行此调用会将 selectedCell 的内容传递给 sender,可以在 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject)

确保您在班级中的某处覆盖了 prepareForSegue。

现在,在prepareForSegue: 中,您可以获得对destinationViewController 的引用,并在destinationViewController 中初始化实例变量,该实例变量将保存您selectedCell 的变量。

//in prepareForSegue
let controller = segue.destinationViewController as detailSuggestion_VC
controller.cellInfo = sender
Run Code Online (Sandbox Code Playgroud)

  • @user10002 好的,感谢您的解释。我知道一种方法可以做到这一点,但您仍然需要将您的 UITableViewCell 类型转换为您的新 tableViewCell 类(您专门为自定义单元格创建的。让我编辑我的答案 (2认同)
  • tableViewCell 是自定义 UITableViewCell 类的名称。无论您将该文件命名为什么。这是阻止您引用单元格属性的主要问题。 (2认同)