ios - 准备从collectionviewcell 中的segue 不显示索引项
问题描述
我正在尝试从 collectionViewController 转到另一个视图控制器,并且我还尝试获取索引并适当地传递数据,但是当我选择一个单元格时,detailVC 只会显示,但没有打印任何内容或任何东西
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == DETAIL_VC {
print("ITEM SELECTED ")
let vc = segue.destination as! DetailVC
guard let selectedIndexPath = sender as? IndexPath else { return }
let flickerPhoto = ServiceProvider.instance.flickerPhotos[selectedIndexPath.item]
print("ITEM SELECTED ")
vc.titleLabel.text = flickerPhoto.title
}
}
什么都没有打印
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let flickerPhoto = ServiceProvider.instance.flickerPhotos[indexPath.item]
let destinationVC = storyboard?.instantiateViewController(withIdentifier: DETAIL_VC) as! DetailVC
destinationVC.titleLabel.text = flickerPhoto.title
}
我得到了错误Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
解决方案
您需要将DETAIL_VC
源vc(而不是单元格)的黄色图标命名的segue连接到目标,并在里面使用它didSelectItemAt
self.performSegue(withIdentifier:DETAIL_VC,sender:indexPath)
当您在加载 vc 之前访问一个为 nil 的插座时它会崩溃,您可以尝试将数据作为字符串发送并将其设置viewDidLoad
在目标 vc 中
destinationVC.titleValue = flickerPhoto.title
class DetailVC:UIViewController {
var titleValue:String = ""
// set it to the label text in `viewDidLoad`
override func viewDidLoad() {
super.viewDidLoad()
self.titleLabel.text = titleValue
}
}
推荐阅读
- javascript - Uncaught SyntaxError: Unexpected token '<' bundle.js line 1 Docker 容器错误
- r - 使用 ggpattern 使用图像创建条形图
- php - 如何使用 laravel eloquent 在 div 中打印 html?
- ruby-on-rails - 为rails Restful API返回不同类型的资源
- python - 从“django.(任何模块)”导入给我这个警告:无法从源代码解决
- reactjs - 我如何处理变量作为变量 - 属性的反应?
- javascript - 如何在 ADYEN 卡组件中存储 state.Data 和 state.isValid?
- python - 使一个类成为常量,谁的类型是它所在的类
- rust - 如何在 Rust 结构实现中编写 SPI DMA 代码?
- c++ - VS Code C++“错误:‘文件系统’不是命名空间名称”