2014年12月10日水曜日

swift基礎 storyBoardを利用しない画面遷移

swiftの基礎まとめ。
storyBoardを利用しないで画面遷移を実装する方法です。

環境

  • Xcode Version 6.1

最初のページへの画面遷移を作成する

AppDelegate.swiftに処理を記載します。 よくありがちなパターンとして、splash画面に遷移させます。splash画面は、SplashViewControllerというクラスにします。


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow!

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window.backgroundColor = UIColor.whiteColor()
        window.rootViewController = UINavigationController(rootViewController: SplashViewController())
        window.makeKeyAndVisible()
        return true
    }

}

windowオブジェクトをForced Unwrappingで宣言しています。
Optional Chainingでも実装可能ですが、エラーはコンパイルでつぶす方向が良いと思います。まあ、好みなのでどちらでも良いと思います。

次のページへの画面遷移を作成する

slash画面では、こにょごにょ処理をやって初期化とかデータを取得したらログイン画面に遷移するのもよくありがちなパターンですね。以下のような感じです。


class SplashViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // something doing
        self.mvLoginView()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func mvLoginView() {
        println("go loginView")
        let loginViewController = LoginViewController()
        navigationController!.pushViewController(loginViewController, animated: true)
    }
    
}

そのまんまの処理です。
mvLoginView関数を呼び出して次のログイン画面に遷移させています。letは定数宣言。直接実体化してもこのサンプルなら問題なし。
navigationControllerは、Forced UnwrappingでpushViewControllerを呼び出します。ここもOptional Chainingでも動きます。

printlnはデバッグ用の関数です。
swiftではデバッグにNSLogではなく、printlnが推奨されています。
NSLogより10倍くらい速いらしいです。

とりあえず画面遷移はこんな感じで記載していくとよいでしょう。swiftは本当にコード量が少なくてスッキリ書けますね。

参照

この記事がお役にたちましたらシェアをお願いします

このエントリーをはてなブックマークに追加

0 件のコメント:

コメントを投稿

Related Posts Plugin for WordPress, Blogger...