Swift中的7种界面传值方式总结(属性传值,构造器传值,通知传值,单例传值,协议传值,闭包传值,NSUserDefaults传值)
之前,我整理过OC的5种基本界面传值方式,很多朋友都有很喜欢,今天再整理一下Swift中的7种常用界面传值供大家参考,不到之处,欢迎各位提点,更多的希望能对大家有所帮助.
注: 文中 ,第一个界面为ViewController,第二个界面为DetailViewController两个界面都会分别有一个Button和一个TextFiled 用于输入值和接受值.来查看传值效果
两个界面的简单搭建及跳转操作如下
//第一个界面ViewController
import UIKit
class ViewController: UIViewController {
fileprivate var tf:UITextField = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
setUpUI()
}
//点击进入第二个界面的按钮进行跳转操作
@objc fileprivate func btnAction() {
let vc = DetailViewController()
navigationController?.pushViewController(vc, animated: true)
}
}
//设置界面
extension ViewController{
fileprivate func setUpUI() {
let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
btn.center = self.view.center
btn.backgroundColor = UIColor.cyan
btn.addTarget(self, action: #selector(btnAction), for: .touchUpInside)
btn.setTitle("进第二个界面", for: UIControlState.normal)
self.view .addSubview(btn)
tf = UITextField(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
tf.center = self.view.center
tf.frame.origin.y = 200
tf.backgroundColor = UIColor.blue
self.view.addSubview(tf)
}
}
//第二个界面DetailViewController
import UIKit
class DetailViewController: UIViewController {
var tf:UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
setUpUI()
}
//点击按钮返回上一界面
func btnAction() {
navigationController?.popViewController(animated: true)
}
extension DetailViewController{
fileprivate func setUpUI() {
let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
btn.center = self.view.center
btn.backgroundColor = UIColor.cyan
btn.addTarget