ustaw początkowy kontroler widoku w appdelegate - swift


147

Chciałbym ustawić początkowy kontroler widoku z appdelegate. Znalazłem naprawdę dobrą odpowiedź, ale jest w celu C i mam problem z szybkim osiągnięciem tego samego.

Programowo ustaw początkowy kontroler widoku przy użyciu scenorysów

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];

    UIViewController *viewController = // determine the initial view controller here and instantiate   it with [storyboard instantiateViewControllerWithIdentifier:<storyboard id>];

    self.window.rootViewController = viewController;
    [self.window makeKeyAndVisible];

    return YES;
}

Czy ktoś może pomóc?

Chcę, aby początkowy kontroler Viewcontroller był zależny od spełnienia pewnych warunków za pomocą instrukcji warunkowej.


To jest możliwy duplikat: stackoverflow.com/questions/10428629/…
— Honey

Odpowiedzi:


279

Użyłem tego wątku, aby pomóc mi przekonwertować obiektyw C na szybki i działa idealnie.

Utwórz wystąpienie i przedstaw viewController w języku Swift

Kod Swift 2 :

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    let initialViewController = storyboard.instantiateViewControllerWithIdentifier("LoginSignupVC")

    self.window?.rootViewController = initialViewController
    self.window?.makeKeyAndVisible()

    return true
}

Kod Swift 3 :

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    self.window = UIWindow(frame: UIScreen.main.bounds)

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    let initialViewController = storyboard.instantiateViewController(withIdentifier: "LoginSignupVC")

    self.window?.rootViewController = initialViewController
    self.window?.makeKeyAndVisible()

    return true
}

1
nie można znaleźć storyboardu „Main” ani „Storyboard.storyboard” w aplikacji Swift 2
— Async-

5
Czy jest to bieżący standardowy sposób ustawiania początkowego kontrolera widoku w appdelegate ? Pytam, bo wygląda to trochę na hack (przepraszam @Abs).
— rigdonmr

10
@rigdonmr Jeśli aplikacja ma scenorys ustawioną jako główny interfejs, okno jest ładowane automatycznie, a jego główny kontroler widoku jest ustawiony na początkowy kontroler widoku scenorysu. Jeśli kontroler widoku wymaga zmiany w oparciu o warunek lub aplikacja nie ma interfejsu głównego, dopuszczalne jest UIWindowprogramowe zainicjowanie i ustawienie głównego kontrolera widoku.
— JAL

2
Zaskakującą (ale dobrą) rzeczą jest to, że ręczne utworzenie instancji kontrolera widoku w ten sposób wydaje się powstrzymywać system iOS przed tworzeniem instancji domyślnego kontrolera widoku. Mogłem się spodziewać, że oba będą załadowane. Czy to zachowanie jest gdzieś udokumentowane?
— Pat Niemeyer

2
@MayankJain to działa dobrze ze Swift 3, wystarczy przetłumaczyć część kodu z wcześniejszego swift
— JAB

42

Spróbuj tego. Na przykład: Powinieneś użyć UINavigationControllerjako początkowego kontrolera widoku. Następnie możesz ustawić dowolny kontroler widoku jako root z serii ujęć.

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let navigationController:UINavigationController = storyboard.instantiateInitialViewController() as UINavigationController
    let rootViewController:UIViewController = storyboard.instantiateViewControllerWithIdentifier("VC") as UIViewController
    navigationController.viewControllers = [rootViewController]
    self.window?.rootViewController = navigationController
    return true
}

Zobacz mój ekran scenorysu.


Czy ustawiłeś identyfikator Storyboard, aby wyświetlić kontroler w scenorysie? Zobacz joxi.ru/l2ZYxZqS8JOomJ
— protikhonoff

Tak już ustawione, myślę, że pomyślnie otwiera kontrolery widoku, ale nie „pokazuje” tego. Jakieś pomysły?
— Abubakar Moallim

Żadnych błędów, po uruchomieniu ekranu pojawia się czarna strona
— Abubakar Moallim

Chyba znalazłem problem. Powinieneś zaznaczyć „Jest początkowym kontrolerem widoku” w swoim storyboardzie. joxi.ru/8AnNbQlhq3QOAO
— protikhonoff

ale chcę zmienić początkowy kontroler widoku za pomocą instrukcji warunkowej.
— Abubakar Moallim

24

Dla Swift 3, Swift 4:

Utwórz instancję kontrolera widoku głównego z serii ujęć:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // this line is important
        self.window = UIWindow(frame: UIScreen.main.bounds)

        // In project directory storyboard looks like Main.storyboard,
        // you should use only part before ".storyboard" as it's name,
        // so in this example name is "Main".
        let storyboard = UIStoryboard.init(name: "Main", bundle: nil)

        // controller identifier sets up in storyboard utilities
        // panel (on the right), it called Storyboard ID
        let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController

        self.window?.rootViewController = viewController
        self.window?.makeKeyAndVisible()        
        return true
    }

Jeśli chcesz użyć UINavigationControllerjako root:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // this line is important
        self.window = UIWindow(frame: UIScreen.main.bounds)

        let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController
        let navigationController = UINavigationController.init(rootViewController: viewController)
        self.window?.rootViewController = navigationController

        self.window?.makeKeyAndVisible()        
        return true
    }

Utwórz instancję kontrolera widoku głównego z XIB:

To prawie to samo, ale zamiast linii

let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController

będziesz musiał pisać

let viewController = YourViewController(nibName: "YourViewController", bundle: nil)

22

jeśli nie używasz scenorysu, możesz spróbować

var window: UIWindow?
var initialViewController :UIViewController?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    initialViewController  = MainViewController(nibName:"MainViewController",bundle:nil)

    let frame = UIScreen.mainScreen().bounds
    window = UIWindow(frame: frame)

    window!.rootViewController = initialViewController
    window!.makeKeyAndVisible()

    return true
}

1
do czego odnosi się nazwa stalówki?
— Abubakar Moallim

@Abs nibName to nazwa końcówki, która ma zostać załadowana w celu utworzenia instancji widoku.
— rashii

Animacje zmiany orientacji przestają z tym działać.
— user3427013

Już zagłosowałem za tym lolem ... "Muszę zainicjować okno, a potem ustawić jego ramkę, zainicjować okno, a potem ustawić jego ramę, muszę zainicjować okno, a następnie ustawić ramkę" -Ja dla siebie
— Chris Allinson

18

Dla nowych Xcode 11.xxx i Swift 5.xx, gdzie docelowy jest ustawiony na iOS 13+.

W przypadku nowej struktury projektu AppDelegate nie musi nic robić w odniesieniu do rootViewController.

Nowa klasa obsługuje klasę okna (UIWindowScene) -> plik 'SceneDelegate'.

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = // Your RootViewController in here
        self.window = window
        window.makeKeyAndVisible()
    }

}

1
Bardzo ceniony.
— Azim Talukdar

14

Oto dobry sposób, aby do tego podejść. Ten przykład umieszcza kontroler nawigacji jako główny kontroler widoku i umieszcza wybrany kontroler widoku na dole stosu nawigacji, gotowy do wypchnięcia z niego wszystkiego, czego potrzebujesz.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
    // mainStoryboard
    let mainStoryboard = UIStoryboard(name: "MainStoryboard", bundle: nil)

    // rootViewController
    let rootViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MainViewController") as? UIViewController

    // navigationController
    let navigationController = UINavigationController(rootViewController: rootViewController!)

    navigationController.navigationBarHidden = true // or not, your choice.

    // self.window
    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

    self.window!.rootViewController = navigationController

    self.window!.makeKeyAndVisible()
}

Aby ten przykład zadziałał, należy ustawić „MainViewController” jako identyfikator serii ujęć na głównym kontrolerze widoku, a nazwa pliku serii ujęć w tym przypadku będzie miała postać „MainStoryboard.storyboard”. W ten sposób zmieniam nazwy moich storyboardów, ponieważ Main.storyboard nie jest dla mnie właściwą nazwą, szczególnie jeśli kiedykolwiek przejdziesz do podklasy.


11

Zrobiłem to z obiektywną nadzieją, że będzie to dla ciebie przydatne

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

UIViewController *viewController;

NSUserDefaults *loginUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *check=[loginUserDefaults objectForKey:@"Checklog"];

if ([check isEqualToString:@"login"]) {

    viewController = [storyboard instantiateViewControllerWithIdentifier:@"SWRevealViewController"];
} else {

    viewController = [storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
}


self.window.rootViewController = viewController;
[self.window makeKeyAndVisible];

Jak zaprojektowałeś kontrolery widoku w scenorysie. Proszę o pomoc.
— Poonam,

przeciągnij kontrolery widoku i ustaw identyfikator storyboardu tożsamości: <ViewControllerName> i uzyskaj dostęp do kontrolera widoku ...
— Patel Jigar

@PatelJigar jak ustawić loginvc
— Uma Madhavi

wywołanie kontrolera widoku, takiego jak ten UITabBarController * tbc = [self.storyboard instantiateViewControllerWithIdentifier: @ "ContentViewController"]; [self presentViewController: tbc animowany: YES zakończenie: nil];
— Patel Jigar

7

Kod dla kodu Swift 4.2 i 5:

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
     self.window = UIWindow(frame: UIScreen.main.bounds)

     let storyboard = UIStoryboard(name: "Main", bundle: nil)

     let initialViewController = storyboard.instantiateViewController(withIdentifier: "dashboardVC")

     self.window?.rootViewController = initialViewController
     self.window?.makeKeyAndVisible()
}

I dla Xcode 11+ and for Swift 5+:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

     var window: UIWindow?

     func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
         if let windowScene = scene as? UIWindowScene {
             let window = UIWindow(windowScene: windowScene)

              window.rootViewController = // Your RootViewController in here

              self.window = window
              window.makeKeyAndVisible()
         }
    }
}

self.window wyświetla błąd Wartość typu „AppDelegate” nie ma „okna” członka, jakieś pomysły?
— Joseph Astrahan

@JosephAstrahan zadeklaruj zmienną przed jej wywołaniem. Jak - var window: UIWindow?.
— Jamil Hasnine Tamim

@JosephAstrahan ponownie sprawdź moją odpowiedź. Dodałem zmienną.
— Jamil Hasnine Tamim

Dzięki, to bardzo pomaga!
— Joseph Astrahan

And for Xcode 11+ and for Swift 5+część bardzo mi pomaga. dzięki stary
— Torongo

6

Zrobiłem w Xcode 8 i swift 3.0 mam nadzieję, że będzie przydatny dla ciebie i będzie działał idealnie. Użyj następującego kodu:

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {       
    self.window = UIWindow(frame: UIScreen.main.bounds)
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let initialViewController = storyboard.instantiateViewController(withIdentifier: "ViewController")
    self.window?.rootViewController = initialViewController
    self.window?.makeKeyAndVisible()
    return true
}

Jeśli używasz kontrolera nawigacji, użyj do tego następującego kodu:

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    self.window = UIWindow(frame: UIScreen.main.bounds)
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let navigationController:UINavigationController = storyboard.instantiateInitialViewController() as! UINavigationController
    let initialViewController = storyboard.instantiateViewControllerWithIdentifier("ViewController")
    navigationController.viewControllers = [initialViewController]
    self.window?.rootViewController = navigationController
    self.window?.makeKeyAndVisible()      
    return true
}

Cześć ... Mayank, zrobiłem w Xcode 8 i swift 3.0 Który błąd pojawia się po użyciu tego rozwiązania, ponieważ działa
— Kunal

6

Swift 4:

Dodaj te wiersze wewnątrz AppDelegate.swift, w ramach funkcji didFinishLaunchingWithOptions () ...

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    // Setting the Appropriate initialViewController

    // Set the window to the dimensions of the device
    self.window = UIWindow(frame: UIScreen.main.bounds)

    // Grab a reference to whichever storyboard you have the ViewController within
    let storyboard = UIStoryboard(name: "Name of Storyboard", bundle: nil)

    // Grab a reference to the ViewController you want to show 1st.
    let initialViewController = storyboard.instantiateViewController(withIdentifier: "Name of ViewController")

    // Set that ViewController as the rootViewController
    self.window?.rootViewController = initialViewController

    // Sets our window up in front
    self.window?.makeKeyAndVisible()

    return true
}

Teraz na przykład wiele razy robimy coś takiego, gdy chcemy albo skierować użytkownika do ekranu logowania, albo do ekranu początkowej konfiguracji, albo z powrotem do ekranu głównego aplikacji itp. Jeśli też chcesz zrobić coś takiego , możesz użyć tego punktu jako rozwidlenia w tym celu.

Pomyśl o tym. Możesz mieć wartość przechowywaną w NSUserDefaults, na przykład zawierającą userLoggedIn Boolean iif userLoggedIn == false { use this storyboard & initialViewController... } else { use this storyboard & initialViewController... }


nie działa w nowym projekcie z 1 dodanym ViewController. Zawsze zaczyna się od początkowego kontrolera widoku. Xcode 11.2 Gdzie może być problem?
— Oleh H

5

Cóż, wszystkie odpowiedzi powyżej / poniżej generują ostrzeżenie o braku punktu wejścia w scenorysie.

Jeśli chcesz mieć 2 (lub więcej) kontrolery widoku wejścia, które zależą od jakiegoś warunku (powiedzmy conditionVariable ), to powinieneś zrobić:

  • W Main.storyboard utwórz UINavigationController bez rootViewController , ustaw go jako punkt wejścia
  • Utwórz 2 (lub więcej) segmentów „Pokaż” do kontrolerów widoku, przypisz im identyfikator, powiedzmy id1 i id2
  • Użyj następnego kodu:

    class AppDelegate: UIResponder, UIApplicationDelegate {
    
       var window: UIWindow?
    
       func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
           let navigationController = window!.rootViewController! as! UINavigationController
           navigationController.performSegueWithIdentifier(conditionVariable ? "id1" : "id2")
    
           return true
       }

Mam nadzieję że to pomoże.


1
błąd „brak punktu wejścia w scenorysie” wynika z konfiguracji projektu, którą można usunąć. przejdź do projektu> informacje> niestandardowe właściwości docelowe systemu iOS i usuń właściwość „Nazwa bazowa pliku głównego scenorysu”. Ostrzeżenie nie powinno się już pojawiać.
— orangemako

5

Jeśli nie używasz scenorysu. Możesz programowo zainicjować główny kontroler widoku.

Szybki 4

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    let rootViewController = MainViewController()
    let navigationController = UINavigationController(rootViewController: rootViewController)
    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = navigationController
    self.window?.makeKeyAndVisible()

    return true
}
class MainViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .green
    }
}

Usuń także Mainz informacji o wdrożeniu .

wprowadź opis obrazu tutaj


To zadziałało ze mną w Swift 4.2, XCode 11.3, IOS 9 ~ 13.3.1
— Coder ACJHP

4

Oto kompletne rozwiązanie w Swift 4 zaimplementuj to w didFinishLaunchingWithOptions

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

 let isLogin = UserDefaults.standard.bool(forKey: "Islogin")
    if isLogin{
        self.NextViewController(storybordid: "OtherViewController")


    }else{
        self.NextViewController(storybordid: "LoginViewController")

    }
}

zapisz tę funkcję w dowolnym miejscu wewnątrz Appdelegate.swift

  func NextViewController(storybordid:String)
{

    let storyBoard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let exampleVC = storyBoard.instantiateViewController(withIdentifier:storybordid )
   // self.present(exampleVC, animated: true)
    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = exampleVC
    self.window?.makeKeyAndVisible()
}

3

Na wypadek, gdybyś chciał to zrobić w kontrolerze widoku, a nie w delegacie aplikacji: po prostu pobierz odwołanie do AppDelegate w kontrolerze widoku i zresetuj jego obiekt okna za pomocą odpowiedniego kontrolera widoku, ponieważ jest to rootviewController.

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let yourVC = mainStoryboard.instantiateViewControllerWithIdentifier("YOUR_VC_IDENTIFIER") as! YourViewController
appDelegate.window?.rootViewController = yourVC
appDelegate.window?.makeKeyAndVisible()

3

Dla Swift 4.0 .

W pliku AppDelegate.swift w metodzie didfinishedlaunchingWithOptions umieść następujący kod.

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    window = UIWindow(frame: UIScreen.main.bounds)
    window?.makeKeyAndVisible()

    let rootVC = MainViewController() // your custom viewController. You can instantiate using nib too. UIViewController(nib name, bundle)
    //let rootVC = UIViewController(nibName: "MainViewController", bundle: nil) //or MainViewController()
    let navController = UINavigationController(rootViewController: rootVC) // Integrate navigation controller programmatically if you want

    window?.rootViewController = navController

    return true
}

Mam nadzieję, że zadziała dobrze.


3
Działa ... Jeśli nie ustawiłeś początkowego viewController w stroyboard, musisz dodać window = UIWindow (ramka: UIScreen.main.bounds)
— Punit

3

Swift 5 i Xcode 11

Więc w xCode 11 rozwiązanie okna nie jest już prawidłowe w appDelegate. Przenieśli to do SceneDelgate. Możesz to znaleźć w pliku SceneDelgate.swift.

Zauważysz, że ma teraz var window: UIWindow?prezent.

W mojej sytuacji używałem TabBarController ze scenorysu i chciałem ustawić go jako rootViewController.

To jest mój kod:

sceneDelegate.swift

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        self.window = self.window ?? UIWindow()//@JA- If this scene's self.window is nil then set a new UIWindow object to it.

        //@Grab the storyboard and ensure that the tab bar controller is reinstantiated with the details below.
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let tabBarController = storyboard.instantiateViewController(withIdentifier: "tabBarController") as! UITabBarController

        for child in tabBarController.viewControllers ?? [] {
            if let top = child as? StateControllerProtocol {
                print("State Controller Passed To:")
                print(child.title!)
                top.setState(state: stateController)
            }
        }

        self.window!.rootViewController = tabBarController //Set the rootViewController to our modified version with the StateController instances
        self.window!.makeKeyAndVisible()

        print("Finished scene setting code")
        guard let _ = (scene as? UIWindowScene) else { return }
    }

Upewnij się, że dodałeś to do właściwej metody sceny, tak jak tutaj. Zauważ, że będziesz musiał ustawić nazwę identyfikatora dla tabBarController lub viewController, którego używasz w scenorysie.

jak ustawić identyfikator scenorysu

W moim przypadku robiłem to, aby ustawić stateController, aby śledzić wspólne zmienne między widokami kart. Jeśli chcesz zrobić to samo, dodaj następujący kod ...

StateController.swift

import Foundation

struct tdfvars{
    var rbe:Double = 1.4
    var t1half:Double = 1.5
    var alphaBetaLate:Double = 3.0
    var alphaBetaAcute:Double = 10.0
    var totalDose:Double = 6000.00
    var dosePerFraction:Double = 200.0
    var numOfFractions:Double = 30
    var totalTime:Double = 168
    var ldrDose:Double = 8500.0
}

//@JA - Protocol that view controllers should have that defines that it should have a function to setState
protocol StateControllerProtocol {
  func setState(state: StateController)
}

class StateController {
    var tdfvariables:tdfvars = tdfvars()
}

Uwaga: Po prostu użyj własnych zmiennych lub czegokolwiek, co próbujesz śledzić, po prostu podałem mój jako przykład w tdfvariables struct.

W każdym widoku TabController dodaj następującą zmienną składową.

    class SettingsViewController: UIViewController {
    var stateController: StateController?
.... }

Następnie w tych samych plikach dodaj następujące elementy:

extension SettingsViewController: StateControllerProtocol {
  func setState(state: StateController) {
    self.stateController = state
  }
}

Co to robi to pozwala uniknąć podejścia singleton do Przekazywanie zmiennych między widokami. Pozwala to łatwo na model iniekcji zależności, który jest znacznie lepszy w dłuższej perspektywie niż podejście singleton.


3

Wyłączyć Main.storyboard

General -> Deployment Info -> Main Interface -> remove `Main` 
Info.plist -> remove Key/Value for `UISceneStoryboardFile` and  `UIMainStoryboardFile`

Dodaj identyfikator scenorysu

Main.storyboard -> Select View Controller -> Inspectors -> Identity inspector -> Storyboard ID -> e.g. customVCStoryboardId

Swift 5 i Xcode 11

Poszerzać UIWindow

class CustomWindow : UIWindow {
    //...
}

Edycja wygenerowana przez Xcode SceneDelegate.swift

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: CustomWindow!

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        guard let windowScene = (scene as? UIWindowScene) else { return }

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "customVCStoryboardId")

        window = CustomWindow(windowScene: windowScene)
        window.rootViewController = initialViewController
        window.makeKeyAndVisible()
    }

    //...
}

Można ustawić kontroler główny na okno kontrolera widoku początkowego .rootViewController = UIStoryboard (nazwa: "Main", bundle: nil) .instantiateInitialViewController ()
— Kamran Khan

1
I worked out a solution on Xcode 6.4 in swift. 

// I saved the credentials on a click event to phone memory

    @IBAction func gotobidderpage(sender: AnyObject) {
 if (usernamestring == "bidder" && passwordstring == "day303")
        {
            rolltype = "1"

NSUserDefaults.standardUserDefaults().setObject(usernamestring, forKey: "username")
NSUserDefaults.standardUserDefaults().setObject(passwordstring, forKey: "password")
NSUserDefaults.standardUserDefaults().setObject(rolltype, forKey: "roll")


            self.performSegueWithIdentifier("seguetobidderpage", sender: self)
}


// Retained saved credentials in app delegate.swift and performed navigation after condition check


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

let usernamestring = NSUserDefaults.standardUserDefaults().stringForKey("username")
let passwordstring = NSUserDefaults.standardUserDefaults().stringForKey("password")
let rolltypestring = NSUserDefaults.standardUserDefaults().stringForKey("roll")

        if (usernamestring == "bidder" && passwordstring == "day303" && rolltypestring == "1")
        {

            // Access the storyboard and fetch an instance of the view controller
            var storyboard = UIStoryboard(name: "Main", bundle: nil)
            var viewController: BidderPage = storyboard.instantiateViewControllerWithIdentifier("bidderpageID") as! BidderPage

            // Then push that view controller onto the navigation stack
            var rootViewController = self.window!.rootViewController as! UINavigationController
            rootViewController.pushViewController(viewController, animated: true)
        }

        // Override point for customization after application launch.
        return true
    }



Hope it helps !

1
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    var exampleViewController: ExampleViewController = mainStoryboard.instantiateViewControllerWithIdentifier("ExampleController") as! ExampleViewController

    self.window?.rootViewController = exampleViewController

    self.window?.makeKeyAndVisible()

    return true
}

1

Otwórz Viewcontroller z delegatem SWRevealViewController z aplikacji.

 self.window = UIWindow(frame: UIScreen.main.bounds)
 let storyboard = UIStoryboard(name: "StoryboardName", bundle: nil)
 let swrevealviewcontroller:SWRevealViewController = storyboard.instantiateInitialViewController() as! SWRevealViewController 
 self.window?.rootViewController = swrevealviewcontroller
 self.window?.makeKeyAndVisible()

0

Dla Swift 5+


var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            let submodules = (
                home: HomeRouter.createModule(),
                search: SearchRouter.createModule(),
                exoplanets: ExoplanetsRouter.createModule()
            )
            
            let tabBarController = TabBarModuleBuilder.build(usingSubmodules: submodules)
            
            window.rootViewController = tabBarController
            self.window = window
            window.makeKeyAndVisible()
        }
    }
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.