美文网首页
swift传值-代理、通知、闭包

swift传值-代理、通知、闭包

作者: 木马不在转 | 来源:发表于2018-07-17 16:11 被阅读28次

一:代理

1.定义协议

protocol ContactViewDelegate:NSObjectProtocol {
 // required
    func setNameViewDidOnClick(name : String)
}

2.声明属性

weak var contactViewDelegate : ContactViewDelegate?

3.代理触发

self.contactViewDelegate?.setNameViewDidOnClick(name: "self")

4.在要实现的类中设置代理

 let vc = testViewController()
vc.contactViewDelegate = self

5.遵循实现协议

class ViewController: UIViewController,ContactViewDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
    }

 func setNameViewDidOnClick(header: String) {
        
    }
}

二:通知

  1. 创建发送通知
let notificationCenterKey = "notificationCenterKey"
let msg = "你有一个消息   "
   
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: notificationCenterKey), object: msg)

  1. 接受通知
  NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: notificationCenterKey), object: nil, queue: OperationQueue.main) { (notif) in
            
        }
  1. 释放通知
//MARK: - 注销通知,相当于OC中的dealloc方法
  deinit {
    
        NotificationCenter.default.removeObserver(self)
    }

三:闭包

  1. 作为属性传值

(1)定义

typealias myBlock = (_ name:String) ->Void

(2)声明属性

var myBlock: myBlock?

(3)调用

 self.myBlock?("我被点击了")

(4)闭包实现

 let vc = testViewController()
        vc.myBlock = {(name:String) ->Void in
            print(name)
        }
  1. 作为方法参数

(1)定义方法

func loadRequest(callBack:(_ name: String) -> Void) {
   
        callBack("哈low我")
    }

(2)调用

  loadRequest { (name) in
            
         print(name)//哈low我
     }

相关文章

网友评论

      本文标题:swift传值-代理、通知、闭包

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