【发布时间】:2017-01-30 01:58:15
【问题描述】:
我正在尝试将字符串类型的新闻 ID 传递给第二个 VC,并从 Realm 加载基于它的对象。当我调试时,我发现准备 segue 正确地将 detailNewsVC.newsID 设置为我的新闻项目的主键,但第二个 VC 没有收到它。对此有什么帮助吗?
我所做的检查:
- 确保详细的 VC 标识符正确
- detailNewsVC.newsID 在 VC 1 中正确设置了新闻 ID .. 这是为了确保领域正确发送 newsID 并且工作正常。
- 将 VC 2 中的 viewDidLoad 更改为 viewWillLoad..只是为了确保之前没有加载第二个 vc,但没有运气。
- 重启xcode
- 将 VC 2 中的 newsID 替换为实际的新闻主键,它可以正确提取相关新闻。我认为罪魁祸首是 VC2 属性:newsID 在调用准备 segue 时没有更新。
为 segue 做准备的第一个 VC 代码:
extension HomeVC: UICollectionViewDelegate {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == SegueIdentifier.gotodetail.rawValue, let sendNewsID = sender as? String {
let navVC = segue.destination as? UINavigationController
let detailNewsVC = navVC?.viewControllers.first as! DetailNewsVC
detailNewsVC.newsID = sendNewsID
print("Detail News ID = \(detailNewsVC.newsID)")
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let newsID = newsArray[indexPath.row].newsId
performSegue(withIdentifier: SegueIdentifier.gotodetail.rawValue, sender: newsID)
}
}
第二个 VC 代码:
class DetailNewsVC: UIViewController {
@IBOutlet private weak var scrollView: UIScrollView!
@IBOutlet private weak var newsTitle: UILabel!
@IBOutlet private weak var newsImage: UIImageView!
@IBOutlet private weak var newsDescription: UILabel!
var newsID = ""
override func viewDidLoad() {
super.viewDidLoad()
let realm = try! Realm()
print("News ID: \(newsID)")
guard let news = realm.object(ofType: News.self, forPrimaryKey: newsID as AnyObject) else {
print("Cannot load news")
return
}
print(news)
newsTitle.text = news.newsTitle
if let url = URL(string: news.urlToImage), let data = try? Data.init(contentsOf: url) {
newsImage.image = UIImage(data: data)
}
newsDescription.text = news.newsDescription
}
}
【问题讨论】:
-
请不要显示代码图片。显示代码。谢谢。
-
哦,还有:您在该代码中记录了很多内容。好主意。请向我们显示该记录的结果。
-
好的。不幸的是,无法完全共享代码。如果有帮助,我可以打印出结果吗?第一个 VC - 详细新闻 ID = 3401CF5C-FCC6-4642-B7D8-31D47C7CC86B 第二个 VC 新闻 ID:此 newsID 为空。
-
发布您展示图片而非图片的代码。由于您已经显示了该代码的图像,因此您至少应该能够发布该代码。与结果相同。将其发布为文本,而不是图像。我们无法搜索图像,我们无法从图像中复制文本并提出更改建议等。
-
刚刚更新。请检查