1.單例模式總結(jié)
final class LTSingle: NSObject {
static let sharedInstance = LTSingle()
private override init() {}
}
//調(diào)用
let shared = LTSingle.sharedInstance
LTLog(shared)
2.屬性傳值總結(jié)
//第二個(gè)控制器 聲明屬性
var postValue: String?
//調(diào)用
if postValue != nil {
LTLog(postValue!)
}
//第一個(gè)控制器
firstVc.postValue = "傳值到下一頁(yè)"
3.代理傳值總結(jié)
//第二個(gè)控制器 聲明協(xié)議
protocol LTDelegate: NSObjectProtocol {
func postValueToUpPage(str: String)
}
//聲明屬性
weak var delegate: LTDelegate?
//點(diǎn)擊事件中調(diào)用
delegate?.postValueToUpPage(str: "傳值到上一頁(yè)")
//第一個(gè)控制器 遵守協(xié)議
firstVc.delegate = self
//實(shí)現(xiàn)代理方法
extension ViewController: LTDelegate {
func postValueToUpPage(str: String) {
LTLog(str)
}
}
4.閉包傳值總結(jié)
//第二個(gè)控制器 聲明閉包
typealias closureBlock = (String) -> Void
//聲明屬性
var postValueBlock:closureBlock?
guard let postValueBlock = postValueBlock else { return }
postValueBlock("傳值到上一頁(yè)")
或者
if postValueBlock != nil {
postValueBlock!("傳值到上一頁(yè)”)
}
//第一個(gè)控制器調(diào)用
firstVc.postValueBlock = { (str) in
print(str)
}
5.通知傳值總結(jié)
//1.注冊(cè)通知
let LTNOTIFICATION_TEST = Notification.Name.init(rawValue: "notificationTest")
NotificationCenter.default.addObserver(self, selector: #selector(receiverNotification(_:)), name: LTNOTIFICATION_TEST, object: nil)
@objc private func receiverNotification(_ notification: Notification) {
guard let userInfo = notification.userInfo else {
return
}
let age = userInfo["age"] as? Int
let key = userInfo["key1"] as? String
if key != nil && age != nil{
print("\(age!)" + "-->" + key!)
}
}
//2.發(fā)送通知
NotificationCenter.default.post(name: LTNOTIFICATION_TEST, object: self, userInfo: ["key1":"傳遞的值", "age" : 18])
//3.移除通知
deinit {
NotificationCenter.default.removeObserver(self)
}