简体   繁体   中英

UITapGestureRecognizer no label in UITableViewCell

I have one little problem.

I implement UIableView like

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell;

    UILabel *label = nil;

    cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];

        UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
        [cell addGestureRecognizer:longPress];

        label = [[UILabel alloc] initWithFrame:CGRectZero];
        [label setLineBreakMode:UILineBreakModeWordWrap];
        [label setMinimumFontSize:self.FONT_SIZE];
        [label setNumberOfLines:0];
        [label setFont:[UIFont systemFontOfSize:self.FONT_SIZE]];
        [label setTag:1];
        [label setBackgroundColor:[UIColor clearColor]];
        [label setTextColor:[colors getMainTextColor]];

        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeCellHeight:)];
        [label addGestureRecognizer:tap];

        [[cell contentView] addSubview:label];

This set UITapGestureRecognizer to the Label and it work but it always tap on the first cell.

Method changeCellHeight always show me that indexPath.row = 1 and I dont know why.

-(void)changeCellHeight:(id)sender{
    UITableViewCell *cell = (UITableViewCell *)[sender view];
    NSIndexPath *IndexPath = [self.table indexPathForCell:cell];
    DataObject * obj_ = [self.allData objectAtIndex:IndexPath.row];
    if (obj_.canChangeHeight) {
        obj_.needChangeHeight = !obj_.needChangeHeight;
        [self.table reloadData];
    }
}

I intentionally put addGestureRecognizer:tap inside if(cell == nil) because I dont want abandoned memory.

But [sender view] isn't a table view cell. It's a label. You're lucky (or unlucky depending on how you look at it) you don't get a crash.

You need to navigate from the label to the cell (superview of superview) and use that instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM