1. 程式人生 > >使用閉包和代理和Segue進行反向傳值

使用閉包和代理和Segue進行反向傳值

closure create 賦值 返回 protocol alt 類型 del uiview

import UIKit

class FirstViewController: UIViewController, SecondViewControllerDelegate {

    @IBOutlet weak var showTextLabel: UILabel!
    @IBOutlet weak var showDelegateTextLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    //點擊按鈕跳轉到SecondViewController
    @IBAction func tapGoSecondViewController(sender: UIButton) {
        //從storyboard上加載SecondViewController
        let secondVC = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()).instantiateViewControllerWithIdentifier("secondViewController") as! SecondViewController
        //實現回調,獲取回調回來的值 (閉包)
secondVC.backClosure = { (backStr: String) -> Void in self.showTextLabel.text = backStr } secondVC.delegate = self //跳轉到SecondViewController self.navigationController?.pushViewController(secondVC, animated: true) } //MARK: - SecondViewControllerDelegate(代理) func fetchBackString(str: String) { self.showDelegateTextLabel.text = str } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
import UIKit //定義閉包類型(特定的函數類型函數類型) typealias InputClosureType = (String) -> Void protocol SecondViewControllerDelegate: NSObjectProtocol{ func fetchBackString(str: String) } class SecondViewController: UIViewController { @IBOutlet weak var inputTextField: UITextField! //接收上個頁面傳過來的閉包塊
var backClosure: InputClosureType? weak var delegate: SecondViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func tapBackButton(sender: UIButton) { if self.backClosure != nil { if let tempString = self.inputTextField.text { self.backClosure!(tempString) } } self.navigationController?.popViewControllerAnimated(true) } @IBAction func delegateBackMethod(sender: UIButton) { if self.delegate != nil { if let tempString = self.inputTextField.text { delegate!.fetchBackString("代理返回數據:\(tempString)") } } self.navigationController?.popViewControllerAnimated(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }

利用Segue進行轉場傳值


正向跳轉

segue正向轉場是prepareForSegue

在源VC中->NavigationViewController在Segue的屬性中選擇show(Xcode7.2沒有show detail),會有返場btn,將VC push進下一個場景。源VC中用prepareForSegue進行設置,在方法中確定目的VC,然後對目的VC中的屬性進行賦值或傳遞方法。

反向轉場

模態展現(modal)的視圖系統不提供返回按鈕。我們需要定義一個反向轉場,可以用模態視圖退場。

在目的視圖定義這個函數

@IBAction func close(segue:UIStoryboardSegue){

裏面放傳遞的數據

}

在跳轉VC中按control拖btn到exit,選擇close。

反向轉場用performSegueWithIdentifier.

btn拖到exit->出口執行目的地VC中的自定義函數

@IBAction func close(segue:UIStoryboardSegue)

{

let sourceVC = segue.sourceViewController as 源VC

(獲取sourceVC中的對象或者數據後在destVC中進行處理)

}

技術分享

使用閉包和代理和Segue進行反向傳值