Search code examples
iosswiftuiviewcontrollerseguepresentviewcontroller

Cannot perform segue to another ViewController after showing the present one with a clear background


I followed Ray Wenderlich tutorial on how to create an iOS book animation, now i'm trying to perform some changes to it.

Original project is composed of Navigation Controller, Books View Controller - showing an array of books, by clicking on a book you can open it - and Book View Controller - showing the selected book open.

What i've added: a View Controller and set it as initial VC; a UIButtonwhich perform a show segue to Navigation Controller.

Here is my storyboard

I want to show View Controller in background after Books View Controller appears but apparently iOS removes the view controllers underneath it from the view hierarchy, this leading to a black background if i set clearColor in the Attributes inspector. I've then added the following code to ViewController.swift to have a transparent background.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let vc = self.storyboard!.instantiateViewControllerWithIdentifier("BooksViewController") as! BooksViewController
    vc.view.backgroundColor = UIColor.clearColor()
    vc.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext
    self.presentViewController(vc, animated: true, completion: nil)
}

It works well and i can see the initial VC in the background while seeing the array of books, but i can no longer perform segue to Book View Controller by clicking on a book. So apparently openBook in BooksViewController is never called:

func selectedCell() -> BookCoverCell? {
    if let indexPath = collectionView?.indexPathForItemAtPoint(CGPointMake(collectionView!.contentOffset.x + collectionView!.bounds.width / 2, collectionView!.bounds.height / 2)) {
        if let cell = collectionView?.cellForItemAtIndexPath(indexPath) as? BookCoverCell {
            return cell
        }
    }
    return nil
}

func openBook(book: Book?) {
    let vc = storyboard?.instantiateViewControllerWithIdentifier("BookViewController") as! BookViewController
    vc.book = selectedCell()?.book
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.navigationController?.pushViewController(vc, animated: true)
        return
    })
}

I cannot understand where the problem is, any help is really appreciated. Please be gentle, i'm still learning Swift and english is not my native language.


Solution

  • You are using prepareForSegue incorrectly. You do not want to present a view controller in your prepareForSegue. Use segue.destinationViewController as! YourViewController to reference it instead