UITableView inside UICollectionView handling touch

2020-05-24 03:40发布

问题:

Collection view consists of a single row, of horizontally aligned cells, which size is the same size as the collection view's bounds, single cell fills entire screen.

The problem is that the collection view seems to be intercepting all of the pans. How can I forward them to the table so I can also scroll the table vertically.

I want vertical pan to be delivered to the table inside the cell, so it can scroll up and down. I want horizontal pan to be delivered to the collection view, so it can scroll horizontally.

Any ideas? Thanks.

回答1:

For UITableView inside CollectionView using storyBoard, please follow these steps:

-Drag CollectionView to UIViewController, drag datasource to UIViewController(don't drag delegate). Add datasource methods inside ViewController.m

-Create Cell:CollectionViewCell class. choose class for Cell in storyBoard to Cell class,specify reuse ID.

-Drag tableView inside collectionCell square. delegate, datasource drag to CollecionCell Square too. Add tableView datasource, delegate inside Cell.m

-Create CellDelegate when implement tableViewDidSelect inside it. Transfer this delegate to UIViewController to perform other action

Sample code: https://github.com/lequysang/github_zip/blob/master/TableViewInCollection.zip



回答2:

Swift2 update - We don't need to do all the above steps. Just making the controller the delegate and datasource of both the tableview and collection view works just fine.



回答3:

I've been able to make this work without using storyboards--although, I use XIBs for my views but only to add the Autolayout rules. All customisation (colors, fonts, labels, etc.) are set in code. In any case, this should also work for cells that are being built programatically.

How to do it:

  • The most important thing to remember is to add your custom view to the contentView property of the cell and not inside the cell itself. If you are using XIBs for the custom UICollectionViewCell, leave it blank. Instantiate your custom view (where the UITableView is), then add it as a subview of the UICollectionViewCell's contentView. If you add the table vie directly inside the collection view cell, the table view will not vertically scroll.

  • Implement shouldSelectItemAtIndexPath and shouldHighlightItemAtIndexPath of the UICollectionViewDelegate and make both return false, so that tapping on the collection view cell does not intercept with taps intended for the table view inside.

Done with Xcode 7.3 for iOS 9+.