在视图控制器之间传递数据,通常有以下几种方法:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationVC = segue.destination as? DestinationViewController {
destinationVC.data = self.data
}
}
protocol DataDelegate {
func passData(data: Any)
}
class SourceViewController: UIViewController {
var delegate: DataDelegate?
func passData() {
delegate?.passData(data: self.data)
}
}
class DestinationViewController: UIViewController, DataDelegate {
func passData(data: Any) {
// 处理传递的数据
}
}
// 发送通知
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "PassDataNotification"), object: nil, userInfo: ["data": self.data])
// 接收通知
NotificationCenter.default.addObserver(self, selector: #selector(receiveData(notification:)), name: NSNotification.Name(rawValue: "PassDataNotification"), object: nil)
@objc func receiveData(notification: Notification) {
if let data = notification.userInfo?["data"] {
// 处理传递的数据
}
}
class DataManager {
static let shared = DataManager()
var data: Any?
}
// 存储数据
DataManager.shared.data = self.data
// 获取数据
if let data = DataManager.shared.data {
// 处理传递的数据
}
以上是在视图控制器之间传递数据的常见方法,具体使用哪种方法取决于具体的需求和场景。
领取专属 10元无门槛券
手把手带您无忧上云