您的位置:首页 > 产品设计 > UI/UE

UITableViewCell中的UILabel添加手势没有响应的解决方法

2013-11-28 18:09 453 查看
有时候自定义UITableViewCell,且cell中添加了一个UILabel,我们的目的是给该label添加一个手势。但是如果按照常规的添加方法,发现所添加的手势并不能响应。以下为解决方法:将手势添加到UITableView上。

@interface TestViewController () <UITableViewDataSource, UITableViewDelegate>

@end

@implementation TestViewController {
UITableView *contentTableView;
}

- (void)viewDidLoad
{
[super viewDidLoad];
//初始化点击手势
UITapGestureRecognizer *tagGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
tagGesture.numberOfTapsRequired = 1;

contentTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
contentTableView.dataSource = self;
contentTableView.delegate = self;
//给tableView添加手势操作
[contentTableView addGestureRecognizer:tagGesture];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellID = @"cellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 50, 30)];
label.tag = 1;
[cell.contentView addSubview:label];
}

UILabel *label = (UILabel *)[cell.contentView viewWithTag:1];
label.text = [NSString stringWithFormat:@"text_%d", indexPath.row];
return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 100.0f;
}

#pragma mark - UITapGestureRecognizer

- (void)tapGesture:(UITapGestureRecognizer *)gesture {

//获得当前手势触发的在UITableView中的坐标
CGPoint location = [gesture locationInView:contentTableView];
//获得当前坐标对应的indexPath
NSIndexPath *indexPath = [contentTableView indexPathForRowAtPoint:location];

if (indexPath) {
//通过indexpath获得对应的Cell
UITableViewCell *cell = [contentTableView cellForRowAtIndexPath:indexPath];
//获得添加到cell.contentView中的UILabel
UILabel *label = nil;
for (UIView *view in cell.contentView.subviews) {
if ([view isKindOfClass:[UILabel class]]) {
label = (UILabel *)view;
break;
}
}

//获得当前手势点击在UILabe中的坐标
CGPoint p = [gesture locationInView:label];
//看看手势点的坐标是不是在UILabel中
if (CGRectContainsPoint(label.frame, p)) {
NSLog(@"label text : %@", label.text);
}
}

}


原文:http://kingiol.com/blog/2013/08/28/uitableview-gesture-control/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐