代码之家  ›  专栏  ›  技术社区  ›  user579911

如何使用通知将字符串数据从swift传递到目标c类

  •  1
  • user579911  · 技术社区  · 7 年前

    我想把表格单元格文本标签数据从swift类传递到目标c类。在swift课堂上,我做了以下几点:,

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

    现在我想用另一个控制器接收这个字符串数据,这是一个目标c类。请引导。

    1 回复  |  直到 7 年前
        1
  •  4
  •   clemens    7 年前

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