UITableViewCell中的UILabel添加手勢沒有響應的解決方法


有時候自定義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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM