swift 也有和OC 一样的穿值方式
1.单例模式总结
final class LTSingle: NSObject {
static let sharedInstance = LTSingle()
private override init() {}
}
2.属性传值
很简单
在下一个界面(ViewController2)中声明
var name : String?
前一个界面(ViewController)中传值
let vc = ViewController2()
vc.name = "测试传值"
self.navigationController?.pushViewController(vc, animated: true)
3.代理
1>在下一个界面(ViewController3)中声明协议
protocol LTDelegate: NSObjectProtocol {
func postValueToUpPage(str: String)
}
2>在class属性(ViewController3)中声明属性
weak var delegate: LTDelegate?
3>ViewController3调用方法
delegate?.postValueToUpPage(str: "传值到上一页")
4>在ViewController2中
class ViewController2: BaseViewController,LTDelegate {
5>在ViewController2遵守协议
let vc = ViewController3()
vc.delegate = self
self.navigationController?.pushViewController(vc, animated: true)
6>在ViewController2实现方法
//实现代理方法
func postValueToUpPage(str: String) {
print(str)
}
4.闭包
1>在下一个界面(ViewController4)中声明
//1.声明
typealias nameBlock = (String) -> Void
2>在class属性(ViewController4)中声明
//2.重定义
var postNameValue:nameBlock?
3>ViewController4调用方法
override func didClick2() {
if postNameValue != nil {
postNameValue!("呵呵")
}
back()
}
4>在ViewController3中
let vc = ViewController4()
vc.postNameValue = { (str) in
print(str)
}
self.navigationController?.pushViewController(vc, animated: true)
貌似闭包更简单一点啊,哈哈
5.通知
1>在ViewController5中按钮点击事件中发送通知
//let dict = ["action":"通知传值"]
//NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationTest"), object: self, userInfo: dict)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationTest"), object: "通知传值")
2>在需要接受的通知的方法中,接受通知
NotificationCenter.default.addObserver(self, selector: #selector(didClick3(notififaction:)), name: NSNotification.Name.init("notificationTest"), object: nil)
3>实现方法
@objc func didClick3(notififaction : NSNotification) {
let name = notififaction.object
print(name as Any)
//print(notififaction.userInfo!["action"] as Any)
}
4>class中移除通知
deinit {
NotificationCenter.default.removeObserver(self)
}
网友评论