这个标题起的好官方😳
有时候,我们的cell中存在textField或其它控件,重写了touch方法注销第一响应,却没有出现我们想要的效果,我们可以添加点击手势解决,但是textField中存在button,button的点击又被手势给吸收了,这就犯了难,如何解决呢?
当当当当,答案来了!
我们可以通过重写tableView来实现!
实现的方法不止一种,也可以用类别来实现,而且,不仅可以用于tableView,也可以用于scrollView
有两个点需要注意一下
-
conformsToProtocol
用来检查对象是否实现了指定协议类的方法 -
respondsToSelector
判断是否有以某个名字命名的方法
写个代理,提供给外部使用
@protocol TouchTableViewDelegate <NSObject>
@optional
- (void)tableView:(UITableView *)tableView
touchesBegan:(NSSet *)touches
withEvent:(UIEvent *)event;
- (void)tableView:(UITableView *)tableView
touchesCancelled:(NSSet *)touches
withEvent:(UIEvent *)event;
- (void)tableView:(UITableView *)tableView
touchesEnded:(NSSet *)touches
withEvent:(UIEvent *)event;
- (void)tableView:(UITableView *)tableView
touchesMoved:(NSSet *)touches
withEvent:(UIEvent *)event;
@end
@interface ZJD_TableView : UITableView
@property (nonatomic,weak) id<TouchTableViewDelegate> touchDelegate;
@end
设置代理属性
@interface TouchTableView : UITableView
{
@private
id _touchDelegate;
}
@property (nonatomic,assign) id<TouchTableViewDelegate> touchDelegate;
@end
点击事件重写
@implementation TouchTableView
@synthesize touchDelegate = _touchDelegate;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];
if ([_touchDelegate conformsToProtocol:@protocol(TouchTableViewDelegate)] &&
[_touchDelegate respondsToSelector:@selector(tableView:touchesBegan:withEvent:)])
{
[_touchDelegate tableView:self touchesBegan:touches withEvent:event];
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesCancelled:touches withEvent:event];
if ([_touchDelegate conformsToProtocol:@protocol(TouchTableViewDelegate)] &&
[_touchDelegate respondsToSelector:@selector(tableView:touchesCancelled:withEvent:)])
{
[_touchDelegate tableView:self touchesCancelled:touches withEvent:event];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesEnded:touches withEvent:event];
if ([_touchDelegate conformsToProtocol:@protocol(TouchTableViewDelegate)] &&
[_touchDelegate respondsToSelector:@selector(tableView:touchesEnded:withEvent:)])
{
[_touchDelegate tableView:self touchesEnded:touches withEvent:event];
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesMoved:touches withEvent:event];
if ([_touchDelegate conformsToProtocol:@protocol(TTWTableViewDelegate)] &&
[_touchDelegate respondsToSelector:@selector(tableView:touchesMoved:withEvent:)])
{
[_touchDelegate tableView:self touchesMoved:touches withEvent:event];
}
}
@end
使用
- (void)loadView
{
[super loadView];
TouchTableView *tableView = [[TouchTableView alloc]initWithFrame:CGRectMake(0.0, 0.0, 320, 460) style:UITableViewStyleGrouped];
tableView.touchDelegate = self;
//相关处理
[self.view addSubview:tableView];
[tableView release];
}
- (void)tableView:(TTWTableView *)tableView
touchesEnded:(NSSet *)touches
withEvent:(UIEvent *)event
{
//touch结束后的处理
}