Instantiate and Present a viewController in Swift

前端 未结 16 1818
难免孤独
难免孤独 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: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
    

提交回复
热议问题