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)
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章