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 使用委托和协议向前和向后传递数据的主要内容,如果未能解决你的问题,请参考以下文章
iOS 8 小部件,在应用程序组之间向前和向后共享数据
GCP数据准备 - 向前和向后填充
如何使用按钮在 UIPageViewController 中向前和向后导航?
每次在libgdx中单击按钮时如何向前和向后移动Sprite?
Java中List向前和向后遍历
播放音频文件以在使用键盘弹奏时向前和向后搜索十秒