【问题标题】:IOS/Swift: Pass Object in tableview to detail view controllerIOS/Swift:将表视图中的对象传递给详细视图控制器
【发布时间】:2018-06-05 11:31:04
【问题描述】:

我正在尝试从 tableview 中获取一个对象并将其传递给详细视图,我知道如何在 Objective-C 中执行此操作,但我是第一次学习 Swift。但是,我的代码没有从索引路径或对象中获取行。

这是我的代码。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        print("segue")
        if segue.identifier == "showDetail"{
                    if let destinationVC = segue.destination as? detailVC {
                                    )
                if let indexPath = self.tableView.indexPathForSelectedRow {      
                    print("row%@",indexPath)//Prints as nil
                let thisItem = myItems[indexPath.row]//never gets here
    destinationVC.item = thisItem 
            }
        }
    }
    }

谁能明白为什么我没有得到行或对象?提前感谢您的任何建议。

编辑:

我得到它与以下工作:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showDetail" {

            let indexPath: NSIndexPath = self.tableView.indexPathForSelectedRow! as NSIndexPath

            let anItem: myItem = myItems[indexPath.row];

            let destVC = segue.destination as? detailVC
            destVC?.item = anItem

        }
    }

【问题讨论】:

    标签: ios swift segue indexpath


    【解决方案1】:

    实现UITableViewDelegate方法,

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let item = myItems[indexPath.row]
        self.performSegue(withIdentifier: "showDetail", sender: item)
    }
    

    然后在下面实现,

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showdetail" {
            let detailController = segue.destination as! detailVC
            detailController.item = sender as! Your_Item
        } 
    }
    

    【讨论】:

    • Your_Item 是什么?它是否记得 item=myItems[indexPath.row] 来自其他方法?
    • 这是你的对象
    • 这里的发送者似乎是UITableCell,而不是对象。所以它试图将表格单元传递给destinationVC,而不是对象:我们正在发送%@ Optional(>)
    • 不会是 UITableViewCell,而是对象
    • myItems 数组中有什么?
    【解决方案2】:

    为什么不使用这些方法来保存所选行或项目的值?然后执行segue?

    tableView(_:didDeselectRowAt:)
    tableView(_:didSelectRowAt:)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多