【问题标题】:"func prepareForSegue" not calling for CollectionView“func prepareForSegue”不调用 CollectionView
【发布时间】:2017-01-11 04:49:57
【问题描述】:

是否可以使用shouldPerformSegueWithIdentifier来捕捉segue的移动,方法如下:

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

这是我的视图控制器代码:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let poke:Pokemon!

    if inSearchMode {
        poke=filterPokemons[indexPath.row]
    } else {
        poke=pokemonlist[indexPath.row]
    }
    shouldPerformSegueWithIdentifier("PokemonDetailVC", sender: poke);
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "PokemonDetailVC" {
        if let detailVC = segue.destinationViewController as? PokemonDetailVC{
            if let poke = sender as? Pokemon {
                detailVC.pokemon=poke;
            }
        }
    }
}

故事板转场参考

【问题讨论】:

    标签: ios swift storyboard swift3


    【解决方案1】:

    试试:

    performSegueWithIdentifier("Identifier", sender: self)
    

    代替:

    shouldPerformSegueWithIdentifier("Identifier", sender: self)
    

    当我们使用shouldPerformSegueWithIdentifier时,我们可以通过以下方法捕捉到segue的移动:

    override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool
    

    查看此链接:Prevent segue in prepareForSegue method?

    【讨论】:

    • 没有sender就可以了,把方法改成performSegueWithIdentifier .就行了
    【解决方案2】:

    您需要调用performSegueWithIdentifier 而不是shouldPerformSegueWithIdentifier,因为shouldPerformSegueWithIdentifier 方法为您提供了防止发生转场的机会。从此方法返回 NO 会导致 segue 无法执行。

    如果您想了解有关shouldPerformSegueWithIdentifier 的更多详细信息,请查看此apple documentation

    performSegueWithIdentifier 方法允许将数据从源视图控制器传递到目标视图控制器。

    所以现在只需像这样调用performSegueWithIdentifier 而不是shouldPerformSegueWithIdentifier

    performSegueWithIdentifier("PokemonDetailVC", sender: poke)
    

    在 Swift 3.0 中

    self.performSegue(withIdentifier: "PokemonDetailVC", sender: poke)
    

    【讨论】:

      猜你喜欢
      • 2016-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-16
      • 2012-03-11
      • 2013-11-03
      • 1970-01-01
      相关资源
      最近更新 更多