Swift Collcetionview didSelectItemAtIndexPath不起作用

在某种情况下,我在情节提要中使用UICollectionViewdidSelectItemAtIndexPath无法正常工作。我在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 ?? "")")
        }
}
heyan602 回答:Swift Collcetionview didSelectItemAtIndexPath不起作用

从collectionViewCell类中删除此行

self.layer.cornerRadius = self.frame.size.width 

更新的代码

class CustomCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        // self.layer.cornerRadius = self.frame.size.width / 2 // remove this line 
    }
}

我认为您需要设置imageView的cornerRadius而不是单元格。

 self.imageView.layer.cornerRadius = self.frame.size.width/ 2
本文链接:https://www.f2er.com/3147270.html

大家都在问