UICollectionView Select and Deselect issue

2019-01-13 00:38发布

So I have a main object that has many images associated with it. An Image is also an object.

Say you have a collection view controller, and in that controller you have

cellForItemAtIndexPath

well based on the main object, if it has the current image associated with it I want to set selected to true. But I want the user to be able to "un-select" that current cell at any time to remove its association with the main object.

I find that if you set "selected to true" - if there is an relation between the main object and image in cellForItemAtIndexPath, de-selection is no longer an option.

in

didDeselectItemAtIndexPath

and

didSelectItemAtIndexPath

I test with a log to see if they are called. If a cell is set to selected - nether gets called, but If I never set a cell to selected in cellForItemAtIndexPath I can select and deselect all I want.

Is this the intended way a collection view is supposed to work? I read the docs and it does not seem to talk about this being so. I interpret the docs to mean it works the way a table view cell would. with a few obvious changes

This also shows the controller is set up correct and is using the appropriate delegate methods.... hmmmm

13条回答
We Are One
2楼-- · 2019-01-13 01:28

Here is my answer for Swift 2.0.

I was able to set the following in viewDidLoad()

collectionView.allowsMultipleSelection = true;

then I implemented these methods

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let cell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCell
    cell.toggleSelected()
}

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    let cell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCell
    cell.toggleSelected()
}

finally

class MyCell : UICollectionViewCell {

    ....

    func toggleSelected ()
    {
        if (selected){
            backgroundColor = UIColor.orangeColor()
        }else {
            backgroundColor = UIColor.whiteColor()
        }
    }

}
查看更多
登录 后发表回答