美文网首页
iOS 代理 && 通知 &&

iOS 代理 && 通知 &&

作者: LuKane | 来源:发表于2018-07-02 18:17 被阅读37次

    代理

    1.设置代理方法

    @objc protocol ViewDelegateControllerDelegate {
        // 必定实现的方法
        func textFieldIsText(_ string : String?)
        
        // 可选实现的方法
        @objc optional
        func textFieldHasText(_ string : String?)
    }
    

    2.设置代理

    // 在 当前类 设置参数的地方
    // 代理属性应该为 weak 类型, 避免无法被释放出现问题
    weak var delegate : ViewDelegateControllerDelegate?
    

    3.在指定的地方让代理实现方法

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

    4.1 实现方 -->遵守协议

    class ViewController: UIViewController,ViewDelegateControllerDelegate 
    

    4.1 实现方 -->设置代理

    let vc = ViewDelegateController()
    vc.delegate = self
    

    4.3 实现方法 --> 完成代理方法

    // 可选实现
    func textFieldHasText(_ string: String?) {
        if string != nil {
            textLabel?.text = string
        }
    }
        
    // 必定实现
    func textFieldIsText(_ string: String?) {
        print(string ?? "")
    }
    

    通知

    1.发送通知

    // 将一个 字典 广播出去
    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.在需要接受广播的地方 添加 通知

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

    3.实现 添加广播的方法

    @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.当控制器 销毁的时候

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

    闭包

    1.声明闭包

    // 传递一个 Int类型的无返回值的 闭包
    var finishCallBack : ((_ index : Int) -> ())?
    

    2.在指定的地方调用 闭包

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

    3.在上一个界面 开始 调用闭包

    let blockVc = ViewBlockController()
    blockVc.finishCallBack = {(_ index) in
        print(index) // 123
    }
    

    相关文章

      网友评论

          本文标题:iOS 代理 && 通知 &&

          本文链接:https://www.haomeiwen.com/subject/kadluftx.html