如何在不呈现数据或 segue 的情况下将数据从"didSelectRowAt"传递到另一个 VC?



我基本上想要的是我想按TableViewController中的一行,然后例如,该行具有的文本并将其传递给当前不存在的ViewController。就像您在Spotify 应用程序中单击一首歌曲时,它会播放它而不显示任何内容,但歌曲详细信息显示在迷你播放器中。

有没有人知道如何做到这一点?

好吧,你可以这样做,但你需要先初始化你的视图控制器,以便你访问它的属性,如:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DestinationVc") as? DestinationVc
vc?.text = "TextToBePassed"
}

它没有呈现它,但我不明白为什么你不想展示或展示它,但这就是根据您的问题完成的方式。谢谢:)

如果您通过XIBprogramatically创建了 UI,请遵循以下方法:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let nextVC = NextViewController()
nextVC.text = model?[indexPath.row].text // If you are using model or if you have stored the data in the array then nextVC.text = yourArray[indexPath.row]["text"]    
self.navigationController?.pushViewController(nextVC,animated: true)
}

另外,在NextViewController,您必须添加文本。喜欢这个:

class NextViewController: UIViewController {
var text = String()
//MARK:- View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
print(text) //This will print the text passed from previous VC
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = NextViewController()
vc.title = "(Title)"
self.navigationController?.pushViewController(vc,animated: true)
}

使用此方法可以帮助您在不使用 segue 的情况下将数据传递到另一个控制器。

假设这是针对iOS的,因为问题没有指定。

UITableViewDelegatetableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)方法中,您可以使用

let cell = tableView.cellForRow(at: indexPath)?.textLabel?.text // cell: String?

然后,如果需要,可以将其分配给全局变量,或者如果您维护对不存在的视图控制器的引用,则可以为其提供一个属性来存储此文本,并在调用performSegue(withIdentifier identifier: String, sender: Any?)之前分配它。

最新更新