UITableView中添加UIButton按钮处理



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    UIButton * accessoryDetailDisclosureButton;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        
        [cell.textLabel setTextColor:[UIColor darkGrayColor]];
        [cell.detailTextLabel setTextColor:[UIColor darkGrayColor]];
        [cell.detailTextLabel setNumberOfLines:4];
        [cell.detailTextLabel setFont:[UIFont systemFontOfSize:12]];
        
        accessoryDetailDisclosureButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
        [accessoryDetailDisclosureButton setImage:[UIImage imageNamed:@"push.png"] forState:UIControlStateNormal];
        [accessoryDetailDisclosureButton setImage:[UIImage imageNamed:@"push_h.png"] forState:UIControlStateHighlighted];


// 加入button单击事件
        [accessoryDetailDisclosureButton addTarget:self action:@selector(accessoryDetailDisclosureButtonPress: event:) forControlEvents:UIControlEventTouchUpInside];
        
        accessoryDetailDisclosureButton.tag = indexPath.row+100;
    }
    else
    {
        accessoryDetailDisclosureButton = (UIButton *)[cell viewWithTag:indexPath.row+100];
    }
  UIImage *image = [UIImage imageNamed:@"Placeholder.png"];
    [cell.imageView setImage:image];

    cell.textLabel.text =@“”;
    cell.detailTextLabel.text =  @“”;
    // Configure the cell...
    cell.accessoryView = accessoryDetailDisclosureButton;
    
    return cell;
    
}

// 检查用户点击按钮时的位置,并转发事件到对应的accessory tapped事件

-(void)accessoryDetailDisclosureButtonPress:(id)sender event:(id)event
{
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:m_tableView];
    NSIndexPath *indexPath = [m_tableView indexPathForRowAtPoint:currentTouchPosition];
    if(indexPath != nil)
    {
        [self tableView:m_tableView didSelectRowAtIndexPath:indexPath];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

//自定义处理
}


类似效果:





你可能感兴趣的:(UITableView中添加UIButton按钮处理)