我在 CollectionViewCell 中有一个 ImageView。我希望能够单击图像,它将我带到另一个视图控制器。我该怎么做?这是我到目前为止的代码。
import UIKit
class FirstViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
var images = ["meal1", "photograph1", "meal1"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.collectionView.delegate = self
self.collectionView.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionViewCell
//set images
cell.imageView.image = UIImage(named: images[indexPath.row])
return cell
}
}
正如您所说,您要检测collectionview
单元格上的图像点击,请通过以下代码:
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.connected(_:)))
cell.yourImageView.isUserInteractionEnabled = true
cell.yourImageView.tag = indexPath.row
cell.yourImageView.addGestureRecognizer(tapGestureRecognizer)
并将以下方法添加到您的视图控制器
func connected(_ sender:AnyObject){
print("you tap image number : (sender.view.tag)")
//Your code for navigate to another viewcontroller
}
注意 - 确保已启用单元格图像的用户交互
将 tabGestureRecognizer 添加到集合视图中的图像视图视图"cellForItemAt"方法中,并在识别器的方法中点击调用 segue 以转到所需的视图控制器。
Swift 5
收藏视图功能:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.tap(_:)))
cell.yourImg.isUserInteractionEnabled = true
cell.yourImg.tag = indexPath.row
cell.yourImg.addGestureRecognizer(tapGestureRecognizer)
return cell
}
点击功能:
@IBAction func tap(_ sender:AnyObject){
print("ViewController tap() Clicked Item: (sender.view.tag)")
}
你可以使用UIButton并在其上设置图像属性而不带标题,也可以将UIGestureRecognizer添加到UIImageView。无论哪种方式,您都可以在收到操作后显示或显示要显示的视图控制器。
在这种情况下,我经常做的一件事是创建一个具有回调函数(类似于buttonPressed:forCollectionCell:
(的 CollectionCellDelegate 协议,我可以让我的 CollectionView 符合该协议,然后将每个单元格的委托设置为 CollectionView。然后,您可以在按下按钮/图像时调用 CollectionView,并让 CollectionView 处理您想要的任何行为,在本例中,显示/推送新的视图控制器。