[swift] 透過protocol資料傳輸(非segue)

Jacob 黃炬楷
Jul 25, 2017 · 4 min read

1.建立protocol,於程式中寫入資料傳輸的方法

protocol CanRecevive {func dataReceived(data: String)}

2. 於接收方之ViewController繼承protocol

class FirstVC: UIViewController, CanRecevive {

3. 並建立資料之傳輸方法

func dataReceived(data: String) {label.text = data}

4. 建立一個property來取用protocol的方法

var delegate: CanReceive?

5. 於執行傳輸動作的Button中,利用delegate來執行protocol的方法,並將textField的內容,寫入protocol方法中的data

delegate?.dataReceived(data: textField.text!)

6. 接收方的 prepare方法中,寫入這個…(我還看不懂,也不會解釋)

secondVC.delegate = self

7. 於執行傳輸動作的Button中,再寫入一個dismiss方法

dismiss(animated: true, completion: nil)

完整code

import UIKitprotocol CanRecevive {func dataReceived(data: String)}class SecondVC: UIViewController {var data = ""var delegate: CanRecevive?@IBOutlet weak var label: UILabel!@IBOutlet weak var textField: UITextField!@IBAction func secondBtn(_ sender: UIButton) {delegate?.dataReceived(data: textField.text!)dismiss(animated: true, completion: nil)}override func viewDidLoad() {super.viewDidLoad()label.text = data}override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()// Dispose of any resources that can be recreated.}}import UIKitclass FirstVC: UIViewController, CanRecevive {var data = ""@IBOutlet weak var label: UILabel!@IBOutlet weak var textField: UITextField!@IBAction func firstBtn(_ sender: UIButton) {performSegue(withIdentifier: "sendToSecond", sender: self)}@IBAction func changeColor(_ sender: UIButton) {changeColor()}func changeColor(){view.backgroundColor = UIColor.blue}func dataReceived(data: String) {label.text = data}override func viewDidLoad() {super.viewDidLoad()label.text = data}override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()// Dispose of any resources that can be recreated.}override func prepare(for segue: UIStoryboardSegue, sender: Any?) {if segue.identifier == "sendToSecond"{let secondVC = segue.destination as! SecondVCsecondVC.data = textField.text!secondVC.delegate = self}}}
    Jacob 黃炬楷

    Written by

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade