我在CollectionViewCell中有一个ImageView。我想能够点击图像,它将我带到另一个ViewController。我该怎么做?这是我到目前为止的代码。
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
}
}
答案 0 :(得分:1)
正如您所说,要检测collectionview
单元格上的图像点按,请仔细阅读以下代码:
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.connected(_:)))
cell.yourImageView.isUserInteractionEnabled = true
cell.yourImageView.tag = indexPath.row
cell.yourImageView.addGestureRecognizer(tapGestureRecognizer)
将以下方法添加到ViewController
func connected(_ sender:AnyObject){
print("you tap image number : \(sender.view.tag)")
//Your code for navigate to another viewcontroller
}
注意 - 确保您的用户与单元格图片的交互已启用
答案 1 :(得分:1)
在collectionView“cellForItemAt”方法中为您的imageview添加tabGestureRecognizer,并在识别器的方法中点击segue以转到所需的viewcontroller。
答案 2 :(得分:1)
快速5
CollectionView功能:
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)")
}
答案 3 :(得分:0)
您可以使用UIButton and set the image property on it但没有标题,也可以添加UIGestureRecognizer to the UIImageView。无论哪种方式,一旦收到动作,你只需要呈现或显示你想要显示的ViewController。
我经常在这种情况下做的一件事是创建一个CollectionCellDelegate协议,它具有一个回调函数(类似buttonPressed:forCollectionCell:
),我可以让我的CollectionView符合,然后设置每个单元格的委托到CollectionView。然后,当按下按钮/图像时,您可以调用CollectionView,并让CollectionView处理您想要的任何行为,在这种情况下,呈现/推送新的视图控制器。