Swiftで遊ぼう! on Hatena

あしたさぬきblogでやってた初心者オヤジのiOSプログラミング奮闘記がHatenaに来ました

Swiftで遊ぼう! - 688 - Multiple MVCs, Segues, and ViewController Lifecycle

今日から講義6です。ちょっと遅れ気味。

Developing iOS 9 Apps with Swift - Free Course by Stanford on iTunes U

マルチプルMVCの話題ですが、切り替え(Segue)を使って制御する内容で私にとって復習になります*1

新しいViewControllerをオブジェクト・ライブラリからMain.storyboardにドラッグ&ドロップします。そしてボタンを4つ並べ(名前は下の図を参照)てStackボタンを使ってコンストレインを設定してレイアウトを調整しまず。次に新しいファイルを作ります。UIViewControllerを継承した「EmotionsViewController」と名前をつけてからプロジェクト内にセーブします。そして再びオブジェクト・ライブラリから「Split View Controller」を選択してドラッグ&ドロップします。いらないViewを消して、SplitViewControllerからEmotionsViewControllerに「Ctrl + ドラッグ」して、メニューウインドウから「mastre view contoller」を選びます。もう一度同じようにFaceViewControllerに「Ctrl + ドラッグ」して「detail view controller」を選んだ状態が次です*2

f:id:yataiblue:20160526165841j:plain

はしょりながら説明します。4つのボタンからFaceViewContorllerに「Ctrl + ドラッグ」して「detail view controller」を選んで4つのセグエを用意します。それぞれのボタンに合わせて「angry」「happy」「worried」「mischievious」をidentifierに設定します。ここは重要なステップです。

NavigationControllerの話もしなきゃいけないと思いますが、あまりにも簡単に実装できるし、過去の記事で何度も実装しているので、ここでは説明しないで次のように実装します。

f:id:yataiblue:20160526210126j:plain

最後にEmotionsViewControllerのコードを次に示します。

private let emotionalFace: Dictionary<String, FacialExpression> = [
    "angry": FacialExpression(eyes: .Closed, 
                              eyeBrows: .Furrowed, 
                              mouth: .Frown),
    "happy": FacialExpression(eyes: .Open, 
                              eyeBrows: .Normal, 
                              mouth: .Smile),
    "worried": FacialExpression(eyes: .Open, 
                                eyeBrows: .Relaxed, 
                                mouth: .Smirk),
    "mischievious": FacialExpression(eyes: .Open, 
                                     eyeBrows: .Furrowed, 
                                     mouth: .Grin)
    ]
    
    
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, 
                              sender: AnyObject?) {
    var destinationvc = segue.destinationViewController
    if let navcon = destinationvc as? UINavigationController {
        destinationvc = navcon.visibleViewController ?? destinationvc
    }
    if let facevc = destinationvc as? FaceViewController {
        if let identifier = segue.identifier {
            if let expression = emotionalFace[identifier] {
                facevc.expression = expression
                if let sendingBUtton = sender as? UIButton {
                    facevc.navigationItem.title = 
                                 sendingBUtton.currentTitle
                }
            }
        }
    }
}

2年前はこういうコードを見たら1日悩んでいましたが、今回は問題なく理解できました。理解できても応用して利用できるかどうか怪しいもんですが。

しかし、これでSplit View ControllerのDetailでもタイトルが表示され、iPhoneでもiPadでも問題なくスムーズに動かせます。

f:id:yataiblue:20160526211732j:plain

コードの説明を希望される人はコメントください。

今日はここまで。

*1:Segueのことが理解できていない人はまず次のページを読んでください->Swiftで遊ぼう! - 273 - Segue(セグエ) - Swiftで遊ぼう! on Hatena

*2:この説明だけで下の状態にできた人は中級レベルのiOSデベロッパーです