Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active March 29, 2017 04:15
Show Gist options
  • Save KentarouKanno/1bedfe2b518d17b63e0eec683e8bc3dc to your computer and use it in GitHub Desktop.
Save KentarouKanno/1bedfe2b518d17b63e0eec683e8bc3dc to your computer and use it in GitHub Desktop.
UIStoryboardSegue

UIStoryboardSegue

★ Unwind Segueでもどった時に遷移前画面のプロパティを取得する

@IBAction func backToTop(segue: UIStoryboardSegue) {
    if let vi = segue.sourceViewController as? ViewController1 {
        print(vi.value)
    }
}

★ 遷移前に遷移先画面を取得する

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if let nextVC = segue.destinationViewController as? ViewController {
        
    }
}

★ Unwind Segueによる画面遷移例

import UIKit

class ViewController: UIViewController {
    

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    // Unwind Segueで呼ばれるメソッド
    @IBAction func unwindFromViewController1(segue: UIStoryboardSegue) {
        
        if segue.identifier == "BackFromViewController1",
            let vc = segue.source as? ViewController1 {
            print("unwindFromViewController1", vc)
        }
    }
}



class ViewController1: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
        
        // 自分でperformSegue(withIdentifier: sender:)を呼んだ時には呼ばれない
        // Unwind Segueで結んだ時に画面遷移をキャンセルできる
        
        // 前画面に戻らない場合はfalseを返す
        
        print("shouldPerformSegue")
        return true
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
        // prepareはunwind SegueでもperformSegueでもどちらでも呼ばれる。
        print("prepare")
    }
    
    @IBAction func segueBack(_ sender: UIButton) {
        
        // 自分でunwind SegueのIdentifierでperformSegueを呼び出す
        performSegue(withIdentifier: "BackFromViewController1", sender: nil)
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment