无法将 TableViewCell 类型的值强制转换为"NSIndexPath"



无法将类型为"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
        }
    }

如何处理此类错误?

为什么不以 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
        }
    }
}

声明一个实例变量

var indexPath: NSIndexPath?

然后像下面这样分配选定的索引路径:

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
            }
        }

希望这对你有帮助。

最新更新