Nailer
Nailer

Reputation: 2426

UITableView inside UICollectionViewCell, all UITableViewCells are highlighted when tapping the cell

I am making a UICollectionView where some of the UICollectionViewCells contain a UITableView.

This works great, and everything is fine until I tap the UICollectionViewCell somewhere else than the UITableView. This causes the setHighlighted method to be called on all UITableViewCells in the table.

Below is a rough scetch of the UICollectionViewCell. The UITableView only spans from "cell one" to "cell three". Tapping anywhere outside this table, but inside the UICollectionViewCell causes the cells to be highlighted.

-------------------------
| Title goes here       |
|                       |
-------------------------
|                       |
|   Cell one            |
-------------------------
|                       |
|   Cell two            |
-------------------------
|                       |
|   Cell three          |
-------------------------
| Button outside table  |
|-----------------------|

The call stack looks something like this.

[MyTableViewCell setHighlighted:]
[UICellHighlightingSupport highlightView:]
UIApplicationMain
main

It seems like the UICollectionViewCell forwards a highlight command to all the cells.

I worked around the issue by overloading the setHighlighted method in my UITableViewCell subclass and not calling the super implementation. This seems a bit hacky though, and I wonder if this behavior can be avoided somehow.

EDIT: I assume this behavior comes from when the UICollectionCellView calls setHighlighted on all its children. Which I understand is useful in most other cases.

Upvotes: 6

Views: 1815

Answers (2)

Mark Krenek
Mark Krenek

Reputation: 4947

To solve this, and to allow the table view cells to be highlighted when directly tapped, and to avoid overriding collectionView:shouldHighlightItemAtIndexPath: since it prevents selection from happening, I overrode UICollectionViewCell's setHighlighted method and reversed the highlighting that it did on my table view cells. This way, my table view cells don't appear highlighted when the collection view is selected.

- (void) setHighlighted:(BOOL)highlighted
{
    [super setHighlighted:highlighted];

    if (highlighted)
    {
        dispatch_async(dispatch_get_main_queue(), ^
        {
            for (UITableViewCell* cell in self.tableView.visibleCells)
                cell.highlighted = NO;
        });
    }
}

I dispatched the highlighting because it appears that UICollectionViewCell delays its highlighting as well. I need my highlighting to happen after UICollectionViewCell's.

Upvotes: 2

micantox
micantox

Reputation: 5616

Have you tried implementing the following UICollectionViewDelegate's method?

collectionView:shouldHighlightItemAtIndexPath:

If you return NO for your UITableView views in the collection view, then you should be good to go.

Upvotes: 2

Related Questions