swift 使用委托和协议向前和向后传递数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 使用委托和协议向前和向后传递数据相关的知识,希望对你有一定的参考价值。

//
//  ViewController.swift
//  Segues 2
//
//  Created by John on 27/03/2018.
//  Copyright © 2018 Rom and Ram. All rights reserved.
//

import UIKit

class FirstViewController: UIViewController, CanReceive {
    
    var dataPassedBack = ""
    

    @IBOutlet weak var label: UILabel!
    
    
    

    
    
    
    @IBOutlet weak var textField: UITextField!
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        
        
        label.text = dataPassedBack
        
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    
    
    
    @IBAction func sendButtonPressed(_ sender: Any) {
        
        performSegue(withIdentifier: "sendDataForwards", sender: self)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "sendDataForwards" {
        
        let secondVC = segue.destination as! SecondViewController
        
        secondVC.data = textField.text!
            
        secondVC.delegate = self
        
    }
    
}
    func dataReceived(data: String) {
        label.text = data
    }
    
    
    
}








------------------------



//
//  SecondViewController.swift
//  Segues 2
//
//  Created by John on 27/03/2018.
//  Copyright © 2018 Rom and Ram. All rights reserved.
//

import UIKit

protocol CanReceive {
    
    func dataReceived(data: String)
}

class SecondViewController: UIViewController {
    
    var delegate : CanReceive?
    
    var data = ""
    
    @IBOutlet weak var textField: UITextField!
    
    
    @IBOutlet weak var label: UILabel!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        label.text = data
        
        

        // Do any additional setup after loading the view.
    }

    
    
  
    
    

    @IBAction func sendDataBack(_ sender: Any) {
        
        delegate?.dataReceived(data: textField.text!)
        dismiss(animated: true, completion: nil)
        }
    }

    




以上是关于swift 使用委托和协议向前和向后传递数据的主要内容,如果未能解决你的问题,请参考以下文章