我正在使用 UICollectionView,其中我有一个带有点击手势识别器的 UIImage 作为我的 CollectionView 的单元格模型。我还有 57 张不同名称的图像,我想根据我点击的图像打印到控制台。
这是我的代码:
import UIKit
class ViewController: UIViewController {
let OLLData = OLLCases()
// MARK: - Outlets
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
// MARK: - Navigation
@IBAction func isSelected(_ sender: Any) {
print("selected \(caseName)")
}
}
//MARK: - Data source
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return OLLData.list.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
let image = OLLData.list[indexPath.item].image
let caseName = OLLData.list[indexPath.item].image
cell.label.text = caseName
cell.imageView.image = UIImage(named: image)
return cell
}
}
然后我有另一个 swift 文件 (PhotoCell),其中我有用于标签和 imageView 的 IBOutlets。
有什么方法可以做到这一点?
谢谢。
最佳答案
您可以使用 UICollectionViewDelegate
方法来检测单元格上的点击,但要使用它,首先您的 UICollectionView
需要确认 delegate
与您的UIViewController
像:
collectionView.delegate = self
在您的 viewDidLoad
方法中。
那么你需要更换
extension ViewController: UICollectionViewDataSource {
与
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate {
并使用委托(delegate)方法
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
你可以使用
获取选定的图像名称let caseName = OLLData.list[indexPath.item].image
print(caseName)
和didSelectItemAt
看起来像:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let caseName = OLLData.list[indexPath.item].image
print(caseName)
}
编辑:
您的扩展
将如下所示:
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return OLLData.list.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
let image = OLLData.list[indexPath.item].image
let caseName = OLLData.list[indexPath.item].image
cell.label.text = caseName
cell.imageView.image = UIImage(named: image)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let caseName = OLLData.list[indexPath.item].image
print(caseName)
}
}
关于swift - 从 UICollectionView 打印图像名称到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55703810/