swift3.0 传值总结(属性、代理、闭包、通知)

swift3.0 传值总结(属性、代理、闭包、通知)


1.单例模式总结
final class LTSingle: NSObject {
    static let sharedInstance = LTSingle()
    private override init() {}
}
调用
let shared = LTSingle.sharedInstance
LTLog(shared)

2.属性传值总结
第二个控制器 声明属性
var postValue: String?
调用
if postValue != nil {
   LTLog(postValue!)
}
第一个控制器
firstVc.postValue = "传值到下一页"


3.代理传值总结
第二个控制器 声明协议
protocol LTDelegate: NSObjectProtocol {
    func postValueToUpPage(str: String)
}
声明属性
weak var delegate: LTDelegate?
点击事件中调用 
delegate?.postValueToUpPage(str: "传值到上一页")
第一个控制器  遵守协议
firstVc.delegate = self
实现代理方法
extension ViewController: LTDelegate {
    func postValueToUpPage(str: String) {
        LTLog(str)
    }
}

4.闭包传值总结 
第二个控制器 声明闭包
typealias closureBlock = (String) -> Void
声明属性
var postValueBlock:closureBlock?
guard let postValueBlock = postValueBlock else { return }
postValueBlock("传值到上一页")
或者
if postValueBlock != nil {
  postValueBlock!("传值到上一页”)
}
第一个控制器调用
firstVc.postValueBlock = { (str) in
   print(str)
}

5.通知传值总结
1.注册通知
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.发送通知
NotificationCenter.default.post(name: LTNOTIFICATION_TEST, object: self, userInfo: ["key1":"传递的值", "age" : 18])
3.移除通知
deinit {
    NotificationCenter.default.removeObserver(self)
}



  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值