版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yyyyccll/article/details/90292154
参考:https://www.cnblogs.com/jige/p/swift_delegate.html
//
// SecondVC.swift
//
import UIKit
//
protocol PassTextDelegate:class {
func passTex(textString : String?)
}
class SecondVC: UIViewController {
var text = UITextField()
//
weak var PassTextDelegate : PassTextDelegate?
override func viewDidLoad() {
super.viewDidLoad()
title = "vc2"
view.backgroundColor = .white
// 输入数据,传给上个页面
text = UITextField(frame: CGRect(x: 100, y: 200, width: 100, height: 30))
text.backgroundColor = .gray
view.addSubview(text)
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 50, height: 30))
button.setTitle("button", for: .normal)
button.addTarget(self, action: #selector(popAction), for: .touchUpInside)
button.backgroundColor = .gray
view.addSubview(button)
}
//
@objc func popAction() {
PassTextDelegate?.passTex(textString: text.text)
self.navigationController?.popViewController(animated: true)
}
}
//
// ViewController.swift
//
//
import UIKit
class ViewController: UIViewController {
var label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
title = "vc1"
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 50, height: 30))
button.setTitle("button", for: .normal)
button.addTarget(self, action: #selector(nextPageAction), for: .touchUpInside)
view.addSubview(button)
button.backgroundColor = .gray
// 接受数据的label
label = UILabel(frame: CGRect(x: 100, y: 200, width: 100, height: 30))
view.addSubview(label)
label.backgroundColor = .gray
}
@objc func nextPageAction() {
let second = SecondVC()
//
second.PassTextDelegate = self
self.navigationController?.pushViewController(second, animated: true)
}
}
//
extension ViewController : PassTextDelegate {
func passTex(textString: String?) {
label.text = textString
}
}