麻烦将自定义单元格值传递给swift中的新viewController

时间:2015-03-20 05:55:22

标签: uitableview swift custom-cell

我有一个使用自定义单元格的tableview。问题是我不知道如何使用prepareForSegue将我的自定义单元格中的textField值传递给下一个视图控制器。我正在使用的代码是:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject) -> PFTableViewCell {

    var cell = tableView.dequeueReusableCellWithIdentifier("StaffCell") as StaffCustomCell!
    if cell == nil {
        cell = StaffCustomCell(style: UITableViewCellStyle.Default, reuseIdentifier: "StaffCell")
    }

    // Extract values from the PFObject to display in the table cell
    cell?.staffNic?.text = object["Nic"] as String!
    cell?.staffApellido?.text = object["Apellido"] as String!

    var initialThumbnail = UIImage(named: "iboAzul")
    cell.staffFoto.image = initialThumbnail
    if let thumbnail = object["FotoStaff"] as? PFFile {
        cell.staffFoto.file = thumbnail
        cell.staffFoto.loadInBackground()
    }

    return cell
}


// Pass the custom cell value to the next view controller
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "segueStaffSeleccionado" {
        let detailViewController = segue.destinationViewController.visibleViewController as StaffDetailViewController

        // This is the code I have no idea how to write. I need to get a value from the selected customCell


    }

有什么想法吗?非常感谢

1 个答案:

答案 0 :(得分:-1)

您可以通过tableView.indexPathForSelectedRow获取所选单元格。使用该indexPath,您可以访问该单元格:

// Pass the custom cell value to the next view controller 
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "segueStaffSeleccionado" {
        let detailViewController = segue.destinationViewController.visibleViewController as StaffDetailViewController

    if let indexPath = self.tableView.indexPathForSelectedRow() {
        let cell = self.tableView.cellForRowAtIndexPath(indexPath)

        // path the cell's content to your detailViewController
        detailViewController.myProperty = cell.textLabel?.text
    }
}

另一个解决方案:如果直接从tableViewCell执行segue(通过ctrl-从InterfaceBuilder中的单元格拖动segue),那么sender就是单元格:

// Pass the custom cell value to the next view controller
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    ...

    if let cell = sender as StaffCustomCell {
        // path the cell's content to your detailViewController
        detailViewController.myProperty = cell.textLabel?.text
    }
}