如何使用通知将字符串数据从 swift 传递到 objective c class
how to pass string data from swift to objective c class using notification
我想将 table 单元格文本标签数据从 swift class 传递到 objective c class。在 swift class 中,我做了以下操作,
class NewsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var newsTableView: UITableView!
var myVC:NewsDetailsViewController!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
print("selected index :",indexPath.row)
let selectedCell = tableView.cellForRow(at: indexPath)
print("did select and the text is \(selectedCell?.textLabel?.text)")
myVC.passedValue = selectedCell?.textLabel?.text
print("text label value: ", myVC.passedValue)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "PostQuestion"), object: myVC.passedValue)
self.present(myVC, animated: true , completion: nil)
}
现在我想用我的另一个控制器接收这个字符串数据,它是 objective c class。请指导。
您应该使用
发送您的通知
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "PostQuestion"),
object: self,
userInfo: ["value": myValue] as Dictionary<AnyHashable, Any>)
并用类似
的方式处理通知
func processNotification(notification: NSNotification) {
let userInfo = notifcation.userInfo
if let value = userInfo?["value"] as? String {
...
}
}
或Objective-C
中相同
- (void)processNotification:(NSNotification *)notification {
NSString *value = [notifcation.userInfo objectForKey:@"value"]
if(value) {
...
}
}
我想将 table 单元格文本标签数据从 swift class 传递到 objective c class。在 swift class 中,我做了以下操作,
class NewsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var newsTableView: UITableView!
var myVC:NewsDetailsViewController!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
print("selected index :",indexPath.row)
let selectedCell = tableView.cellForRow(at: indexPath)
print("did select and the text is \(selectedCell?.textLabel?.text)")
myVC.passedValue = selectedCell?.textLabel?.text
print("text label value: ", myVC.passedValue)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "PostQuestion"), object: myVC.passedValue)
self.present(myVC, animated: true , completion: nil)
}
现在我想用我的另一个控制器接收这个字符串数据,它是 objective c class。请指导。
您应该使用
发送您的通知NotificationCenter.default.post(name: NSNotification.Name(rawValue: "PostQuestion"),
object: self,
userInfo: ["value": myValue] as Dictionary<AnyHashable, Any>)
并用类似
的方式处理通知func processNotification(notification: NSNotification) {
let userInfo = notifcation.userInfo
if let value = userInfo?["value"] as? String {
...
}
}
或Objective-C
中相同- (void)processNotification:(NSNotification *)notification {
NSString *value = [notifcation.userInfo objectForKey:@"value"]
if(value) {
...
}
}