我在 TableView 中有 CollectionView。一切都很好,但是。当我想将我的单元格导航到另一个 viewController 时出现错误
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let bookView: BookSingleController = storyboard.instantiateViewControllerWithIdentifier("BookSingle") as! BookSingleController
self.navigationController?.pushViewController(bookView, animated: true)
bookView.bookID = "\(self.books[indexPath.row].id)"
print(self.books[indexPath.row].id)
}
Xcode 在 self.navigationController?.pushViewController(bookView, animated: true) 行上显示错误。这是错误描述:
Value of 'RelatedBookTableViewCell' has no member 'navigationController'
RelatedBookTableViewCell 是我的自定义单元格类:
class RelatedBookTableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout
我的问题在哪里?
谢谢。
最佳答案
您需要:
- 像一些人建议的那样使用委托(delegate)模式。
您将调用从 collectionView 委托(delegate)方法 didSelectItemAtIndexPath
传递到单元格上您自己的自定义委托(delegate)/协议(protocol),显示该单元格的 UITableViewController 是该单元格的委托(delegate)。这可以在 cellForRowAtIndexPath 中设置。
swift
自定义协议(protocol)
协议(protocol) DisplayBookDelegate {
func displayBook(bookId: String)
}
在tableViewController中
class tableViewController: UITableViewController, DisplayBookDelegate {
...
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.delegate = self
return UITableViewCell()
}
func displayBook(let bookId) {
self.navigationController?.pushViewController(bookView, animated: true)
}
}
在单元格中
var delegate: DisplayBookDelegate?
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.delegate.displayBook("1")
}
- 使用通知并在通知对象的字典中传递
bookId
objc: [[NSNotificationCenter defaultCenter] postNotificationName:"kDisplayBookView"object:@{"bookId":"1"}];
swift NSNotificationCenter.defaultCenter().postNotificationName("kDisplayBookView", object: ["bookId":"1"])
关于iOS Swift 自定义 Cell NavigationController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39117644/