iOS Swift 自定义 Cell NavigationController

标签 ios objective-c swift uitableview uicollectionviewcell

我在 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

我的问题在哪里?

谢谢。

最佳答案

您需要:

  1. 像一些人建议的那样使用委托(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")
}
  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/

相关文章:

objective-c - UITableView Cells 的图像改变了吗?

objective-c - 在 Swift 中使用 Objective-C 时,Xcode 无法识别 CGFloat/UIFont/CGSize

iphone - 在运行时浏览核心数据内容(通过 Xcode 模拟器)

iphone - UIPageViewController 在旋转时重置为第一页

ios - 准备 segue 函数不加载新值

ios - 在 Xamarin 中,当以编程方式将约束添加到 subview 时,如何更改 super View 的框架?

ios - 传输安全已阻止明文 HTTP

ios - 使用索引在annotationView中显示文本数组

ios - 在 UINavigationController 中,topViewController、visibleViewController、presentedViewController 之间有什么区别?

swift - 我可以在 UserDefaults 上存储哪种类型的字典或数组有任何限制吗?