我已经将UITableView(作为KRTableView)子类化并实现了四种基于触摸的方法(touchesBegan,touchesEnded,touchesMoved和touchesCancelled),以便我可以检测何时在UITableView上处理基于触摸的事件 . 基本上我需要检测的是当UITableView向上或向下滚动时 .
但是,子类化UITableView并创建上述方法只能检测UITableViewCell内的滚动或手指移动,而不是整个UITableView .
一旦我的手指移动到下一个单元格,触摸事件就不会做任何事情 .
这就是我为UITableView创建子类的方法:
#import "KRTableView.h"
@implementation KRTableView
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
NSLog(@"touches began...");
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesMoved:touches withEvent:event];
NSLog(@"touchesMoved occured");
}
- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent *)event {
[super touchesCancelled:touches withEvent:event];
NSLog(@"touchesCancelled occured");
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesEnded:touches withEvent:event];
NSLog(@"A tap was detected on KRTableView");
}
@end
如何检测UITableView何时向上或向下滚动?
3 回答
您不需要拦截事件方法 . 检查
UIScrollViewDelegate
协议的文档,并根据您的具体情况实施-scrollViewDidScroll:
或-scrollViewWillBeginDragging:
方法 .我想补充以下内容:
如果您正在使用
UITableView
,则可能已经在实施UITableViewDelegate
以使用数据填充表格 .协议UITableViewDelegate符合UIScrollViewDelegate,因此您需要做的就是直接在UITableViewDelegate实现中实现方法
-scrollViewWillBeginDragging
和-scrollViewDidScroll
,如果将实现类设置为UITableView的委托,它们将自动调用 .如果您还想拦截表中的点击而不仅仅是拖动和滚动,您可以扩展并实现自己的UITableViewCell并在其中使用touchesBegan:方法 . 通过组合这两种方法,您应该能够在用户与UITableView交互时完成大部分操作 .
这是我的错误,我试图在重新加载tableview之前调用该方法 . 以下代码帮助我解决了这个问题 .
[mytableview reloadData];
[mytableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:btn.tag-1] atScrollPosition:UITableViewScrollPositionTop animated:YES];