简体   繁体   中英

(Swift) didSelectItemAtIndexPath in UICollectionView defined in external view doesn't work

This is my problem. I have made a View Controller which inherited from UIViewController, UICollectionViewDataSource and UICollectionViewDelegate. So, I have this:

class myController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
...
}

And then, I made a custom view that it has a UICollectionView, something like this:

class externalCollectionView: UIView {
    var myCollection: UICollectionView?

    override init(frame: CGRect){
        super.init(frame: frame)
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20)
        layout.itemSize = CGSize(width: 130, height: 130)
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10

        myCollection = UICollectionView(frame: CGRectMake(0, 120, frame.size.width, frame.size.height - 120), collectionViewLayout: layout)
        myCollection!.registerNib(UINib(nibName: "customCellView", bundle: nil), forCellWithReuseIdentifier: "myItem")

        self.addSubview(myCollection!)
    }
}

So, into my view controller I set delegate methods and features with this code in the viewDidLoad method:

    customView = externalCollectionView(frame: self.view.frame)
    customView.myCollection!.dataSource = self
    customView.myCollection!.delegate = self
    customView.myCollection!.userInteractionEnabled = true
    customView.myCollection!.allowsMultipleSelection = true

with this, the method didSelectItemAtIndexPath never is called. Yes, I have a custom cell collection view (in a xib), but I even have made it without graphical elements (empty) and the method is not called. I have implemented several solutions that I have found on Internet but nothing works. Anyone have idea what is happen?

have you tried to connect from Storyboard or Xib your UICollectionViewCell to file's owner delegate and dataSource? maybe this could help

You just have to set userInteractionEnabled to true for the custom view. If the parent view has no user interaction enabled, then it's subviews won't recognise any touch events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM