【发布时间】:2018-06-25 11:07:54
【问题描述】:
我想将数据从一个 VC 解析到另一个 VC,以打开一个带有给定数据作为 URL 字符串的 web 视图。数据来自表格视图。在表格视图中,我有一个带有打开 segue 功能的按钮。
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath, object: PFObject?) -> PFArchivTableViewCell? {
let cell = tableView.dequeueReusableCell(withIdentifier: "PFCell") as! PFArchivTableViewCell?
cell?.button.addTarget(self, action: #selector(someAction), for: UIControlEvents.touchUpInside)
cell?.button.accessibilityHint = object?.object(forKey: "calameoURL") as? String} return cell
然后我为按钮使用一个函数:
@objc func someAction(sender: UIButton) {
let PFurlString = sender.accessibilityHint!
print ("URL in the cell: \(PFurlString)")
self.performSegue(withIdentifier: "showPFArchivUrl", sender: AnyObject.self)
}
以及为转场做准备:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showPFArchivUrl" {
let destination = segue.destination as? ArchivWebViewController
print ("button pressed")
destination?.dataFromFirst = "Hello World"
destination?.PFurlString? = PFurlString!
}
}
问题是:ArchivWebViewController中传递的字符串“Hello World”可用,但给定的变量“PFurlString”始终为零。有没有人想在另一个视图控制器上获取这个变量?
非常感谢您的回答。我更改了以下几行:
let cell = tableView.dequeueReusableCell(withIdentifier: "PFCell") as! PFArchivTableViewCell
cell.button.addTarget(self, action: #selector(someAction), for: UIControlEvents.touchUpInside)
cell.button.accessibilityHint = object?.object(forKey: "calameoURL") as? String
在按钮的函数中,我在打印语句中获得了 accessibilityHint 的值。
但在 prepare(for segue: UIStoryboardSegue, sender: Any?) 中,值始终为 nil
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showPFArchivUrl" {
let destination = segue.destination as! ArchivWebViewController
print ("URL: \(PFurlString)")
destination.PFurlString = PFurlString
}
【问题讨论】:
-
您使用了太多的感叹号和问号。例如语法
as! PFArchivTableViewCell?(强制向下转换一个可选项到一个可选项)是没有意义的。删除?。建议强制解包在运行时不能失败的可选项,因为它们会发现设计错误。使用可选的向下转换没有任何反应,您也不知道为什么。强制解包目标视图控制器:let destination = segue.destination as! ArchivWebViewController。如果发生崩溃,则说明 segue 有问题。
标签: swift4