【问题标题】:Pass data from CollectionViewCell into NavigationItem.title on 2nd ViewController将数据从 CollectionViewCell 传递到第二个 ViewController 上的 NavigationItem.title
【发布时间】:2014-12-17 23:30:06
【问题描述】:

更新,请参阅下面的评论,因为我做错了。认为有人可能会从所有这些新手错误中受益:):我有一个带有部分标题和单元格标题(UILabels)的 collectionView,它是通过 cloudkit 动态输入的。我能够让代码最终选择一个单元格,然后将单元格的标题发送到第二个 ViewController 的 navigationItem.title 属性。

但是,现在第二个 ViewController 在第一次出现后正在重新加载。我在导航控制器中嵌入了第一个 CollectionViewController。我在情节提要中创建了一个从 CollectionView 中的原型单元到第二个 ViewController 的推送转场,并为转场提供了一个标识符。知道为什么它在第一次出现后再次重新加载第二个 ViewController 吗?

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {


     self.performSegueWithIdentifier("selected", sender: indexPath)


}


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "selected" {


        let indexPaths : NSArray = self.collectionView!.indexPathsForSelectedItems()
        let indexPath : NSIndexPath = indexPaths[0] as NSIndexPath

        let theSelectedItem = sections[indexPath.section].category[indexPath.item]


        let svc = segue.destinationViewController as TableViewControllerNew
        svc.navigationItem.title = theSelectedItem

        // I created the tableview controller in the storyboard, and then subclassed the UITableViewController, and set the storyboard tableview controller's class to the subclass in the identity inspector
    }

【问题讨论】:

  • 没关系!我发现了问题....新手错误!我没有意识到如果你在故事板中有一个转场,你不需要也调用“performSegueWithIdentifier”。希望这篇文章可以帮助别人。另外,在 prepareForSegue 方法中找到了代码的替代版本,它更短。而不是上面 indexPaths 和 indexPath 的两行,替换为以下行:let indexPath: NSIndexPath = self.collectionView!.indexPathForCell(sender as CollectionViewCell)!

标签: swift collectionview


【解决方案1】:

didSelect... 方法中设置self.navigationItem.title = ...,然后在您的第一个VC 的viewWillAppear 方法中将其重置为旧标题。这将使您不必在第一个 VC 中创建一个全局变量,或者不必将标题作为属性传递给您的第二个 VC,尽管这两种解决方案都应该可以工作。

【讨论】:

  • 谢谢!然而,就在你发表评论之前,我终于在这个网站上找到了一个足够相似的例子。但是现在我有一个新问题..请参阅上面的新 cmets/code。欣赏任何见解!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多