facebook twitter hatena line email

Ios/swift/画面遷移

提供: 初心者エンジニアの簡易メモ
2016年8月5日 (金) 20:45時点におけるAdmin (トーク | 投稿記録)による版 (戻るボタンを追加)

(差分) ←前の版 | 最新版 (差分) | 次の版→ (差分)
移動: 案内検索

遷移先のViewController.swift作成

  1. プロジェクトからNewFileを作成しSwiftFileを作成する
  2. 名前をSecondViewControllerとする
  3. するとSecondViewController.swiftがつくられる

以下の通りSecondViewController.swiftを書き換える

import UIKit
class SecondViewController: UIViewController {
   override func viewDidLoad() {
       super.viewDidLoad()
       self.view.backgroundColor = .redColor()
   }
   override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
   }
}

遷移先のViewControllerのstoryboardを作成する

  1. storyboardのオブジェクトからViewControllerをstoryboardに貼り付ける
  2. 上部の3つのボタンのうち一番左をクリックしCustomClass名に"SecondViewController"と入力する

遷移元画面に遷移ボタンを設置&アクションを追加

  1. buttonオブジェクトを遷移元画面のStroyboardに貼り付ける
  2. butoonをクリックし、Controlを押したまま遷移先画面にドラッグ
  3. action->showを選択する
  4. シミュレーションを実行し、画面遷移を確認

画面遷移時のデータ渡し

  • ViewController.swfit
   override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
       var secondViewController:SecondViewController = segue.destinationViewController as! SecondViewController
       secondViewController.sendText = self.testlabel.text
   }
  • SecondViewController.swift
import UIKit
class SecondViewController: UIViewController {
   @IBOutlet weak var label2: UILabel!
   var sendText:String? = "initdata"
   override func viewDidLoad() {
       super.viewDidLoad()
       self.view.backgroundColor = .redColor()
       self.label2.text = self.sendText
   }
   override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
   }
}

戻るボタンを追加

  1. 遷移元のViewController.swiftに以下追加
   @IBAction func back(segue:UIStoryboardSegue){
       print("back")
   }
  1. 遷移先の画面にButtonを追加し、そのButtonをExitボタン(上の3つのマークのうち一番右)にドラッグしbackを選択

コードで戻る

通常の場合

self.dismissViewControllerAnimated(true, completion: nil)

ナビゲーションの場合

self.navigationController?.popViewControllerAnimated(true)

参考:http://qiita.com/omatty198/items/cb037b8aa8b9b410be03

参考

http://qiita.com/h_nagami/items/66dc637463f98716bfa5 ViewController作成 http://qiita.com/39_isao/items/5f09c96a8a4c2de7c8fe 画面遷移によるデータ渡し