这里讲的传值方式主要有四种:页面属性传值、NSUserDefaults、协议传值、闭包block传值。均以两个控制器SecondViewController和threeViewController传值为例:
1、页面属性传值
(一)、单纯代码跳转传值:
SecondViewController:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let threeVC = storyboard.instantiateViewController(withIdentifier: "threeViewControllerID") as! threeViewController
threeVC.myStr="控制器2向控制器3传值"
self.present(threeVC, animated: true, completion: nil)
threeViewController:
var myStr=String()//全局变量
override func viewDidLoad() {
super.viewDidLoad()
print("页面属性传值:\(myStr)"
}
(二)、storyboard拉线跳转,页面参数传递:
SecondViewController:
//拉线跳转页面传值
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let theSegue=segue.destination as! threeViewController
theSegue.myStr="这是通过另一种方式传值"
}
threeViewController:与上面的相同。
2.通过userDefault存储数据:这个可以多页面间传值
UserDefaults().setValue("王珊", forKey: "userName")//存数据
UserDefaults().string(forKey: "userName") ?? ""//取数据
3.协议传值:
反向传值为例:点击返回按钮返回到上一个页面并传递参数。
threeViewController:
//(一)要创建一个协议,写在class之前
protocol FTVCdelegte : NSObjectProtocol{
//在协议里面,声明许多方法
// 第一个,改变标题
func change(title:String)
//第二个,改变背景色
func ChangeColoer (Coloer:UIColor)
//是否成功的标志
func ChangSucces(YON:Bool)
}
//(二)创建一个遵守协议的对象,写在定义属性处。
var delegate_zsj:FTVCdelegte?
//(三)点击返回,传递参数
@IBAction func backBtnAction(_ sender: UIButton) {
delegate_zsj?.change(title: "首页")
delegate_zsj?.ChangeColoer(Coloer: UIColor.red)
delegate_zsj?.ChangSucces(YON: true)
self.navigationController?.popViewController(animated: true)
}
SecondViewController:
//(四)继承代理:
class SecondViewController: UIViewController,FTVCdelegte,ChangeBtnDelege{...
//(五)实现协议方法:必须全部实现
//更改主题名字
func change(title: String) {
self.title = title
}
//更改背景色
func ChangeColoer(Coloer: UIColor) { self.view.backgroundColor = Coloer
}
//是否成功
func ChangSucces(YON: Bool) {
print(YON)
}
//(六)跳转页面时挂上代理
@IBAction func tiaozhuanBtnAction(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let threeVC = storyboard.instantiateViewController(withIdentifier: "threeViewControllerID") as! threeViewController
threeVC.delegate_zsj = self
self.navigationController?.pushViewController(threeVC, animated: true)
}
4.闭包(block)传值:
反向传值为例:点击返回按钮返回到上一个页面并传递参数。
threeViewController:
//(一)声明一个block方法:
var bbchange:((_ title:String,_ myColor:UIColor)->Void)?
//(二)返回上一个页面并传递参数:
@IBAction func backBtnAction(_ sender: UIButton) {
bbchange?("文档",UIColor.green)
self.navigationController?.popViewController(animated: true)
}
SecondViewController:
//(三)跳到下一级页面调用block方法
@IBAction func tiaozhuanBtnAction(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let threeVC = storyboard.instantiateViewController(withIdentifier: "threeViewControllerID") as! threeViewController
threeVC.bbchange={
( title:String,myColor:UIColor) in
self.title=title
self.view.backgroundColor=myColor
}
self.navigationController?.pushViewController(threeVC, animated: true)
}