こんにちは、はじめです。
ようやくswift3のコードを書きながらの勉強を開始しました。
まだまだかなりの初心者なので最近学んだコードでの画面遷移の書き方を復習もかねて
記事にしてみようと思います。
・Swift 3.1
・Xcode 8.3.2
まずは下の画像のように2つのViewControllerを用意します。
1.ViewControllerのファイル名、class名を「FirstViewController」に変更
2.storyboardにてViewControllerSceneのCustomClassに「FirstViewController」を設定
3.SecondViewController.swiftファイルを作成し、FirstViewController.swiftの中身をコピペ
4.SecondViewController.swiftのclass名を「SecondViewController」に変更
5.storyboardにViewControllerを追加して、CustomClassnに「SecondViewController」を設定
6.遷移したことがわかるようにSecondViewControllerにLabelを追加し、「SecondView」と記述しておく
FirstViewControllerからSecondViewControllerへのSegueを作成し、
identifierに「toSecondViewSegue」と登録
1.FirstViewControllerにButtonを追加しテキストを「NEXT PAGE」に変更
2.controlを押しながら、buttonからFirstViewController.swiftにドラッグ&ドロップ
3.tapNextPageButtonというactionメソッドを作成
tapNextPageButton()に以下を記述
performSegue(withIdentifier: "toSecondViewSegue", sender: nil)
以上で「NEXT PAGE」のボタンを押すとSecondViewに遷移させることができます。
次に遷移先に何か値を渡す方法としてprepareを使って見たいと思います。
事前準備としてはperformSegueの時と同様なので省略します。
1.FirstViewControllerにbuttonを追加
2.追加したbuttonからSecondViewControllerへのsegueを作成
3.作成したSegueのidentifierに「toSecondViewSegue」と登録
1.遷移元から渡される値を受け取るためSecondViewControllerのclass内に以下を追加
var labelText = ""
2.SecondViewControllerにあるLabelを「myLabel」という名前でoutlet接続する
@IBOutlet weak var myLabel: UILabel!
3.値を受け取っていることがわかるように以下のようにする
override func viewDidLoad() { super.viewDidLoad() myLabel.text = labelText }
FirstViewControllerに以下を追加
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "toSecondViewSegue") { let vc: SecondViewController = segue.destination as! SecondViewController vc.labelText = "次の画面です" } }
上のコードで
1.画面遷移が行われる前にsegueのidentifierが”toSecondViewSegue”かどうかを確認
2.”toSecondViewSegue”だった場合SecondViewControllerのlabelTextに”次の画面です”と定義
という流れで処理を行った後に画面遷移が行われます。
performSegueとprepareを組み合わせたものに関しては
もう少し理解を深めた上で書いた方が良いと思いましたので次回また記述してみようと思いました。
ピッカービューもまだ使用したことがないので、今後記事にしてみようと思っております。