iOS 代理 && 通知 && 閉包 回調(diào) - Swift

代理

1.設(shè)置代理方法

@objc protocol ViewDelegateControllerDelegate {
    // 必定實(shí)現(xiàn)的方法
    func textFieldIsText(_ string : String?)
    
    // 可選實(shí)現(xiàn)的方法
    @objc optional
    func textFieldHasText(_ string : String?)
}

2.設(shè)置代理

// 在 當(dāng)前類(lèi) 設(shè)置參數(shù)的地方
// 代理屬性應(yīng)該為 weak 類(lèi)型, 避免無(wú)法被釋放出現(xiàn)問(wèn)題
weak var delegate : ViewDelegateControllerDelegate?

3.在指定的地方讓代理實(shí)現(xiàn)方法

if (self.delegate != nil) {
    self.delegate?.textFieldHasText!(self.textField?.text)
}
    
if (self.delegate != nil){
    self.delegate?.textFieldIsText(self.textField?.text)
}

4.1 實(shí)現(xiàn)方 -->遵守協(xié)議

class ViewController: UIViewController,ViewDelegateControllerDelegate 

4.1 實(shí)現(xiàn)方 -->設(shè)置代理

let vc = ViewDelegateController()
vc.delegate = self

4.3 實(shí)現(xiàn)方法 --> 完成代理方法

// 可選實(shí)現(xiàn)
func textFieldHasText(_ string: String?) {
    if string != nil {
        textLabel?.text = string
    }
}
    
// 必定實(shí)現(xiàn)
func textFieldIsText(_ string: String?) {
    print(string ?? "")
}

通知

1.發(fā)送通知

// 將一個(gè) 字典 廣播出去
var dict : [String : Any] = [String : Any]()
dict["id"] = 123
dict["name"] = "textName"
dict["avatar"] = "https://www.xxxx.png"
    
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ViewNotificationTextDidBack"), object: nil, userInfo: dict)

2.在需要接受廣播的地方 添加 通知

// 通知名稱 和 發(fā)送 通知的名稱保持一致
NotificationCenter.default.addObserver(self, selector: #selector(textDidNotificateBack(_:)), name: NSNotification.Name(rawValue: "ViewNotificationTextDidBack"), object: nil)

3.實(shí)現(xiàn) 添加廣播的方法

@objc func textDidNotificateBack(_ dict: Notification){
    let name = dict.name._rawValue
    let userInfo : [String : Any] = dict.userInfo as! [String : Any]
    print(name,userInfo) // ViewNotificationTextDidBack ["id": 123, "name": "textName", "avatar": "https://www.xxxx.png"]
}

4.當(dāng)控制器 銷(xiāo)毀的時(shí)候

deinit {
    // 注意 : 這里是 移除所有的通知, 也可以移除指定的通知
    NotificationCenter.default.removeObserver(self)
//  NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "ViewNotificationTextDidBack"), object: nil)
}

閉包

1.聲明閉包

// 傳遞一個(gè) Int類(lèi)型的無(wú)返回值的 閉包
var finishCallBack : ((_ index : Int) -> ())?

2.在指定的地方調(diào)用 閉包

if self.finishCallBack != nil {
    self.finishCallBack?(123)
}

3.在上一個(gè)界面 開(kāi)始 調(diào)用閉包

let blockVc = ViewBlockController()
blockVc.finishCallBack = {(_ index) in
    print(index) // 123
}
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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