swift

swift 传值总结(属性、代理、闭包、通知)

2018-03-29  本文已影响21人  buzaixian程序员

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)  
} 
上一篇下一篇

猜你喜欢

热点阅读