LoginSignup
0
0

More than 5 years have passed since last update.

在 iOS 初始化視窗 - Swift 3 調整記

Posted at

引言

這週開始準備遷移到 Swift 3 的開發環境。週末就來嘗試一下「這些東西在 Swift 3 要怎麼寫」。

目前有發現比較大的差別是

  • Foundation Framework 的 NS 基本上都被摘掉了
  • GCD 的寫法有改變
  • 許多原生 SDK 的 singleton 要透過方法才能取用,更新之後變成只需要用成員變數的方式取得即可。也就是後面不用再加上 () ,有的名稱也比較簡潔。

這篇則是要筆記,在 App Delegate 裡面要怎麼初始化自己的 UIWindow ,並初始化自己的 view controller 並顯示出來。

原本的寫法

首先, MyViewController 是一個繼承 UIViewController 的一個子類別,可以任意換成自己需要的初始畫面。

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

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

    // 如果你的 view controller 是"不需要"透過 nib 來初始化,可以用這行
    // self.window?.rootViewController = MyViewController()

    // 如果你的 view controller 是要透過 nib 來初始化,就是這行
    self.window?.rootViewController = MyViewController(nibName: "MyViewController", bundle: nil)

    self.window?.makeKeyAndVisible()

    return true
}

在 iOS 10 SDK 之後的寫法

變化其實沒有很大,如下:

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

    self.window = UIWindow(frame: UIScreen.main.bounds)

    // 如果你的 view controller 是"不需要"透過 nib 來初始化,可以用這行
    // self.window?.rootViewController = MyViewController()

    // 如果你的 view controller 是要透過 nib 來初始化,就是這行
    self.window?.rootViewController = MyViewController(nibName: "MyViewController", bundle: nil)

    self.window?.makeKeyAndVisible()

    return true
}

在這幾行程式碼裡面,有變動的基本上就只有取用 "mainScreen()" 這段而已,從原本的:

UIScreen.mainScreen()

換成這樣

UIScreen.main

想法和小結

其實剛換到 Swift 開發的時候,一開始有在發牢騷:為什麼 singleton 的變數必須要用 method 去取用?

每一個 singleton 後面都要掛上 () 其實也覺得有點多餘,現在終於可以拿掉了!
而且在根據使用情境在更加簡化了變數命名,也少了一些重複的贅字,覺得這是個好的方向。

以上,繼續再來去看有被換掉什麼東西 :smile:

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0