在某种情况下,我在情节提要中使用UICollectionView
。 didSelectItemAtIndexPath
无法正常工作。我在UICollectionView上添加了Imageview
并使用了customcell。
CollectionView CustomCell
class CustomCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
override func draw(_ rect: CGRect) {
super.draw(rect)
self.layer.cornerRadius = self.frame.size.width / 2
}
}
我的CollectionView代表
class ModernViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.allowsSelection = true
}
// MARK: CollectionView Delegate
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
return self.listData
}
func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",for: indexPath as IndexPath) as! CustomCollectionViewCell
let item = self.listData[indexPath.item]
let url = item.profileimage
cell.imageView?.sd_setImage(with: URL(string: url ?? "sample.png"),placeholderImage: UIImage(named: "sample.png"))
return cell
}
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 35.0,height: 35.0)
}
func collectionView(_ collectionView: UICollectionView,didSelectItemAt indexPath: IndexPath) {
print("You selected cell #\(indexPath.item)!")
//let item = self.listData[indexPath.item]
//print("SELECTED COLLECTION CELL: \(item.firstname ?? "")")
}
}