属性传值:
顾名思义,常用的就是从前往后传值;属性传值一共分为三步:
1、定义一个要与传值数据类型相同的属性
2、给属性赋值
3、取出属性中的值
// 随便写的一个方法
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//同OC一样,首先给要跳转到的页面初始化
let pushVC = PushViewController()
//str: 下个界面的属性,将"属性传值" 这个字符串传到下个界面
pushVC.str = "属性传值"
//跳转
self.navigationController?.pushViewController(pushVC, animated: true)
}
跳转到改界面
class PushViewController: UIViewController {
//属性传值
//此处定义的str,为的是在上个界面跳转的时候要传的属性
var str: String!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print("str:=====\(str)")
}
}

代理传值:
1、定义协议
2、定义代理属性
3、代理对象所在类遵循协议
4、代理对象所在类遵循协议
5、代理对象所在类实现协议中的方法
6、通知代理对象干活
//代理传值1:
//首先定义一个协议
protocol PushViewControllerDeleget {
//需要遵守的协议方法
func sendValue(text:String)
}
//代理传值2:
//此处可以理解为OC中的(@property(nonatomic,weak) id<PushViewControllerDeleget>delegate;)
var delegate: PushViewControllerDeleget!
//代理传值3
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//此行代码可以理解为在OC中的:
/**
if ([self.delegate respondsToSelector:@selector(sendValue:text)]) {
[self.delegate sendValue:text];
}
*/
self.delegate.sendValue(text: "代理传值")
self.navigationController?.popViewController(animated: true)
}
//代理传值4:
//跟OC一样,想让谁遵守协议,就写在哪里(注意是用","分开)
class HomeViewController: UIViewController, PushViewControllerDeleget { }
//代理传值5
class HomeViewController: UIViewController, PushViewControllerDeleget {
/** 注意:遵守的协议方法要写在这里,写在" viewDidLoad "里面是报错的 */
// 定义一个label,假如传值给label
var lable = UILabel()
//遵守协议方法:sendValue
func sendValue(text: String) {
//text:为传过来的值,将text的值 赋值给lable.text
lable.text = text
print(lable.text!)
}
}

闭包传值
从后往前传值
1、定义一个闭包属性
2、在前一个界面为闭包属性赋值
3、在pop回去之前调用闭包
//闭包传值1:
//定义一个闭包
var value: ((String) ->())!
//闭包传值2:
let pushVC = PushViewController()
pushVC.value = { (text: String) in
// 取出参数,为前一个界面的赋值
self.lable.text = text
print(self.lable.text!)
}
//闭包传值3:
self.value("闭包传值")

NotificationCenter传值
注意:Swift3.0之后,这里不再是NSNotificationCenter了,方法变动很大。
通知使用步骤:注册通知 -> 发送通知 -> 移除通知
- 注册通知
//注册成为观察者
//参数1:观察者对象
//参数2:消息中心发送消息的时候观察者会自动调用的方法对应的selector(观察者接收到消息后会调用的方法)-->必须带一个参数,并且参数的类型是NSNotification
//参数3:观察者要观察的消息的名字
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "notifyName"), object: nil, queue: OperationQueue.main) { (note) in
//这里拿到通知传来的数据text,然后进行逻辑处理, 我们这里只是打印传过来的内容
print("\(String(describing: note.userInfo?["text"])))")
}
- 发送通知
//使用消息中心发送消息(消息的内容就是要传的值)
//a.拿到消息中心(单例对象)NotificationCenter.default
//b.发送消息
//NSNotification.Name(rawValue:"notifyName") 消息名,Swift3.0之后的写法
//userInfo:要发送的消息的内容
NotificationCenter.default.post(name: NSNotification.Name(rawValue:"notifyName"), object: self, userInfo: ["text":"这是一个通知"])
- 移除通知
deinit {
//方式1:直接self
NotificationCenter.default.removeObserver(self)
//方式2:移除指定的名字notifyName
//NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "notifyName"), object: nil)
}

到这里,常用的几种传值的简单使用就介绍完了。
代码:https://github.com/Baiyongyu/Swift-RootController.git
网友评论