【发布时间】:2018-04-25 00:24:36
【问题描述】:
我的收藏视图中有 2 个部分:图片和相册。 每个部分都有自己的逻辑。通过点击相册 - 一些照片被上传。 通过单击图像我想访问出口 UIView 变量,但我不能因为内部类中的 didSelectItemAt indexPath 方法。
class TwoViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
@IBOutlet var pickedPhotoView: UIView!
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! AlbumCell
<b>// Here is ok. i can access the pickedPhotoView variable</b>
view.addSubview(pickedPhotoView)
}
class ImagesCell: UICollectionViewCell, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// but here there is no chance to access pickedPhotoView variable
}
}
更新:
class TwoViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, ImagesCellDelegate {
func doSomething(_ sender: ImagesCell) {
print("do something")
}
var imagesCell: ImagesCell = ImagesCell()
override func viewDidLoad() {
super.viewDidLoad()
imagesCell.delegate = self
}
}
protocol ImagesCellDelegate {
func doSomething(_ sender: ImagesCell)
}
class ImagesCell: UICollectionViewCell, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var delegate: ImagesCellDelegate!
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.doSomething(self)
}
}
doSomething 函数未在 TwoViewController 中执行。 我想我做错了什么:
var imagesCell: ImagesCell = ImagesCell()
imagesCell.delegate = self
有什么想法吗? 谢谢!
解决办法是:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
cell.delegate = self
}
【问题讨论】:
-
为什么单元格冒充集合视图委托?让控制器成为代表...
-
Mohit Athwani,我该怎么做?
标签: ios swift xcode collectionview