Instantiate and Present a viewController in Swift

前端 未结 16 1540
难免孤独
难免孤独 2020-11-22 13:04

Issue

I started taking a look of the new Swift on Xcode 6, and I tried some demo projects and tutorials. Now I am stuck at:

相关标签:
16条回答
  • 2020-11-22 13:28

    If you want to present it modally, you should have something like bellow:

    let vc = self.storyboard!.instantiateViewControllerWithIdentifier("YourViewControllerID")
    self.showDetailViewController(vc as! YourViewControllerClassName, sender: self)
    
    0 讨论(0)
  • 2020-11-22 13:29

    No matter what I tried, it just wouldn't work for me - no errors, but no new view controller on my screen either. Don't know why, but wrapping it in timeout function finally made it work:

    DispatchQueue.main.asyncAfter(deadline: .now() + 0.0) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "TabletViewController")
        self.present(controller, animated: true, completion: nil)
    }
    
    0 讨论(0)
  • 2020-11-22 13:34

    I would like to suggest a much cleaner way. This will be useful when we have multiple storyboards

    1.Create a structure with all your storyboards

    struct Storyboard {
          static let main = "Main"
          static let login = "login"
          static let profile = "profile" 
          static let home = "home"
        }
    

    2. Create a UIStoryboard extension like this

    extension UIStoryboard {
      @nonobjc class var main: UIStoryboard {
        return UIStoryboard(name: Storyboard.main, bundle: nil)
      }
      @nonobjc class var journey: UIStoryboard {
        return UIStoryboard(name: Storyboard.login, bundle: nil)
      }
      @nonobjc class var quiz: UIStoryboard {
        return UIStoryboard(name: Storyboard.profile, bundle: nil)
      }
      @nonobjc class var home: UIStoryboard {
        return UIStoryboard(name: Storyboard.home, bundle: nil)
      }
    }
    

    Give the storyboard identifier as the class name, and use the below code to instantiate

    let loginVc = UIStoryboard.login.instantiateViewController(withIdentifier: "\(LoginViewController.self)") as! LoginViewController
    
    0 讨论(0)
  • 2020-11-22 13:37
    guard let vc = storyboard?.instantiateViewController(withIdentifier: "add") else { return }
            vc.modalPresentationStyle = .fullScreen
            present(vc, animated: true, completion: nil)
    
    0 讨论(0)
提交回复
热议问题