【问题标题】:Buttons with push segues on superview of collectionviewcell which has storyboard segue throws error在具有情节提要 segue 的 collectionviewcell 的 superview 上带有 push segues 的按钮会引发错误
【发布时间】:2015-11-23 10:46:15
【问题描述】:

我是 swift 新手,我被这个错误困住了。我有一个 viewController,它有一个集合视图,它有一个 viewContoller 的故事板 segue 和两个按钮,它们有一个 push segue 到其他一些 viewController。当我尝试点击这些按钮时,会出现一个致命错误,即 sender 不是具有以下代码的 collectionView。

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) 
{
    if let cell = collectionViewOne.cellForItemAtIndexPath(indexPath) 
    {
        performSegueWithIdentifier("showDeals", sender: cell)
    } 
    else 
    {
        // Error indexPath is not on screen: this should never happen.
    }
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    assert(sender as? UICollectionViewCell != nil, "sender is not a collection view")

    if let indexPath = self.collectionViewOne?.indexPathForCell(sender as! UICollectionViewCell) {
        if segue.identifier == "showDeals" {
            let detailVC: DealsTableViewController = segue.destinationViewController as! DealsTableViewController
            detailVC.someCategory = MyIds[indexPath.row]
        }
    } else {
        // Error sender is not a cell or cell is not in collectionView.
    }
}

【问题讨论】:

  • 不确定这是不是答案,但您应该先检查标识符是否为 showDeals,然后再进行其余的操作。
  • 我已经检查了标识符,它似乎是 showDeals。

标签: ios swift uicollectionview segue


【解决方案1】:

尝试添加

print("sender type : \(sender.dynamicType)")

在您的 prepareForSegue 中,不要使用断言,而是使用可选链接来强制转换发件人变量:

if let cell = sender as? UICollectionViewCell 

而不是:

assert(sender as? UICollectionViewCell != nil, "sender is not a collection view")

【讨论】:

  • 您的回答非常完美。对我来说工作得很好。非常感谢。
  • 顺便说一句,我认为如果您将 != 更改为 ==,assert 将起作用,这就是它与 assert 一起使用的方式。
  • 我没有说它不起作用我只是说最好在 else 中捕获错误,因为如果他部署的是应用程序,断言将不起作用,但 else 会。如果他使用断言,应用程序将在 (sender as!UICollectionViewCell) 处崩溃,但如果他不这样做,他可以简单地在 else 中打印一个可理解的错误,并且应用程序不会崩溃
  • 我们知道它是如何工作的,Venkata 不知道。这是对文卡塔的评论;-)
猜你喜欢
  • 2014-01-06
  • 2012-05-03
  • 1970-01-01
  • 2014-12-01
  • 2012-05-20
  • 1970-01-01
  • 2014-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多