swift 傳值總結(jié)(屬性、代理、閉包、通知)

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)  
} 
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容