[英]Could not cast value of type TableViewCell to 'NSIndexPath'
Could not cast value of type 'Google_Books_1.BookTableViewCell' (0x105557600) to 'NSIndexPath' (0x1061cb438) 无法将类型'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
}
}
How to handle such error? 如何处理此类错误?
Declare an instance variable 声明一个实例变量
var indexPath: NSIndexPath?
Then assign selected indexPath like bellow: 然后像下面这样分配选定的indexPath:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// let contact = ContactList![indexPath.row]
self.indexPath = indexPath
performSegueWithIdentifier("BookDetailSegue", sender: indexPath)
}
Now access the indexPath like this: 现在像这样访问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
}
}
Hope this help you. 希望这对您有所帮助。
Why not base yourself on your tableView's indexPathForSelectedRow
property instead? 为什么不基于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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.