如何在UIScrollView中使用UITableView并接收单元格单击?

我有我的应用程序中显示为一个单独的屏幕DiscountListTableViewController 。 但还有另一个屏幕( PlaceDetailsViewController ),我需要在底部显示相关的折扣。

目前, PlaceDetailsViewController.view具有UIScrollView作为一个容器,我将DiscountListTableViewController.tableView添加到PlaceDetailsViewController viewDidLoad中的这个UIScrollView.content容器。 这工作和表视图显示正确,但无法接收单元格点击。

我知道UITableViewUIScrollViewinheritance,它不知道(但不是限制)。 但是,从松耦合的angular度来看,每个组件都应该被devise成可以在别处独立使用的一种方式,在我的情况下,它是DiscountListTableViewController

PlaceDetailsViewController组件仅仅需要DiscountListTableViewController ,所以没有理由不能直接使用它。 有什么build议么?

答:不要这样做。

UITableview从—-> UIScrollView : UIView : UIResponder : NSObjectinheritance

苹果说:

重要说明:您不应该在UIS​​crollView对象中embeddedUIWebView或UITableView对象。 如果这样做,可能会导致意外的行为,因为两个对象的触摸事件可能会混淆并被错误地处理。

不build议? 在阅读完这本书之后,感觉就像“不这样做”。 不可预测性对于应用程序来说从来就不是一个好的行为

重要说明:您不应该在UIS​​crollView对象中embeddedUIWebView或UITableView对象。 如果这样做,可能会导致意外的行为,因为两个对象的触摸事件可能会混淆并被错误地处理。

将分享如何解决这个问题。 分类了UIScrollView并在PlaceDetailsViewController中用作容器视图:

 @interface PlaceDetailsContainerUIScrollView : UIScrollView @end @implementation PlaceDetailsContainerUIScrollView - (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent *)event { UIView *result = [super hitTest:point withEvent:event]; if ([result isKindOfClass:[UIView class]] && (result.tag == kDiscountListTableViewCellTag) { UITableView *tableView = (UITableView *) [[result.superview superview] superview]; return tableView; } return result; } @end 

另外,不要忘记设置PlaceDetailsContainerUIScrollView.delaysContentTouches = YES和PlaceDetailsContainerUIScrollView.canCancelContentTouches = NO。

另外,在DiscountListTableViewController方法中需要小的修复:

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { DiscountDetailsViewController *discountDetailsVC = [[DiscountDetailsViewController alloc] init]; //[self.navigationController pushViewController:discountDetailsVC animated:YES]; // self.navigationController is nill because it's not pushed on nav stack, so will grab the current one: AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; [appDelegate.navigationController pushViewController:discountDetailsVC animated:YES]; }