无法将TableViewCell类型的值转换为' NSIndexPath'

时间:2016-06-12 09:35:26

标签: ios swift

无法投放类型' Google_Books_1.BookTableViewCell' (0x105557600)到' NSIndexPath' (0x1061cb438)

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("BookCell", forIndexPath: indexPath) as!BookTableViewCell
  ...
}


func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        // let contact = ContactList![indexPath.row]
        performSegueWithIdentifier("BookDetailSegue", sender: indexPath)
    }
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        // let contact = ContactList![indexPath.row]
        performSegueWithIdentifier("BookDetailSegue", sender: indexPath)
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "BookDetailSegue" {
            let vc = segue.destinationViewController as! BookDetailViewController

            let indexPath = sender as! NSIndexPath
            vc.book = self.bookList[indexPath.row] **//error is here**
            vc.index = indexPath.row
        }
    }

如何处理此类错误?

2 个答案:

答案 0 :(得分:0)

声明实例变量

var indexPath: NSIndexPath?

然后将所选的indexPath分配给bellow:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
            // let contact = ContactList![indexPath.row]
            self.indexPath = indexPath
            performSegueWithIdentifier("BookDetailSegue", sender: indexPath)
        }

现在像这样访问indexPath:

 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
            if segue.identifier == "BookDetailSegue" {
                let vc = segue.destinationViewController as! BookDetailViewController

                vc.book = self.bookList[self.indexPath.row!] **//error is here**
                vc.index = indexPath.row
            }
        }

希望这对你有所帮助。

答案 1 :(得分:0)

为什么不以您的tableView' indexPathForSelectedRow属性为基础?

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "BookDetailSegue" {
        let vc = segue.destinationViewController as! BookDetailViewController
        if let indexPath =  tableView.indexPathForSelectedRow {
            vc.book = self.bookList[indexPath.row] **//error is here**
            vc.index = indexPath.row
        }
    }
}