Swift performSegueWithIdentifier shows black screen

自闭症网瘾萝莉.ら 提交于 2019-11-29 18:04:43

I've build your app and everything works, maybe you've missed something, here is my solution (Note: Code is in Swift 3.0, but should be easy to adopt it to Swift 2.*):

The storyboard:

Set the segueToTraits identifier:

Set the TraitViewController class as custom class in the storyboard:

The view controller with the buttons:

import UIKit

class ViewController: UIViewController {  

  let boyGender = "boy"
  let girlGender = "girl"
  var selectedGender: String?


  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "segueToTraits"{
      if let gender = self.selectedGender {
        let traitVC = segue.destination as? TraitViewController
        traitVC!.gender = gender
      }
    }
  }

  func sendGenderToTraitsView(gender : String?){
    performSegue(withIdentifier: "segueToTraits", sender: self)

  }

  @IBAction func button1(sender: UIButton) {
    selectedGender = boyGender
    self.sendGenderToTraitsView(gender: selectedGender)
  }


  @IBAction func button2(sender: UIButton) {
    selectedGender = girlGender
    self.sendGenderToTraitsView(gender: selectedGender)
  }

}

The trait view controller:

import UIKit

class TraitViewController: UIViewController {


  var gender: String = ""

  override func viewDidLoad() {
    super.viewDidLoad()

    print("gender: \(gender)")
  }

}

Result:

You can find the sample project here

By following the steps that @ronatory had laid out so well for me in the accepted answer, I was able to see that I had set up my TraitViewController as a UIPageViewController instead of UIViewController.. and so it didn't generate any errors, but it just took me to a black screen. Feel silly that I read through my code so many times and never noticed this.

Main point: If you're getting a black screen on a ViewController randomly, make sure your class is extending the correct parent class. in my case:

class TraitViewController: UIPageViewController {

needed to be

class TraitViewController: UIViewController {
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!