如何动态地将UIButton添加到UITableViewCell?

时间:2011-12-26 07:31:24

标签: iphone ios ios4

我想动态地将UIButton添加到表格单元格中 - 请参阅以下要求。

当用户选择一个单元格时,我只是在

中调整该表格单元格的高度
-(void) tableView:(UITableView*) tableView didSelectRowAtIndexPath:(UIIndexPath*) indexPath {
        selIndPath = [indexPath retain];
        [self.tableView beginUpdates];
        [self.tableView endUpdates];
}

上述方法强制tableView调整所选行的高度。但是当我在上面的方法中添加UIButton时,按钮不可见。

我对[self.tableView reloadData];

不感兴趣

非常感谢任何帮助。

** * ** EDITED * ** * ***

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (selIndPath && selIndPath == indexPath) {
        //UITableViewCell* cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
//      UIButton* btn = (UIButton*)[[cell contentView] viewWithTag:1234];
//      btn.frame = CGRectMake(40, 60, 60, 24);
//      [cell setNeedsDisplay];
        return 90;
    }
    return 64;
}

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        [[cell contentView] setBackgroundColor:[UIColor clearColor]];
        [[cell backgroundView] setBackgroundColor:[UIColor clearColor]];
    }

    // THIS LINES OF CODE WORKS ONLY ON reloadData
    if (selIndPath && selIndPath == indexPath) {
        UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(40, 60, 60, 24);
        btn.tag = 1234;
        [btn setTitle:@"Hi" forState:UIControlStateNormal];
        [cell.contentView addSubview:btn];
    }

    // Configure the cell.
    cell.textLabel.text = @"Loading..";
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    selIndPath = [indexPath retain];
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
    //[self.tableView reloadData];
    [self.tableView beginUpdates];
    [self.tableView endUpdates];
}

1 个答案:

答案 0 :(得分:2)

如果您将按钮添加到cellForRowAtIndexPath中的单元格,则无法添加该按钮:。您需要做的是创建自定义UITableViewCell(请参阅此问题的答案 - Changing the position of custom UIButton in custom UITableViewCell

在“自定义”单元格中,创建方法

-(void) addButtonToCell
{
   UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(40, 60, 60, 24);
    btn.tag = 1234;
    [btn setTitle:@"Hi" forState:UIControlStateNormal];
    [self.contentView addSubview:btn];

}

当然,你如何添加按钮以及你传递给这种方法的参数是由你决定的,但你得到了要点。

cellForRowAtIndexPath:中,只需添加

即可
if (selIndPath && selIndPath == indexPath) {
[cell addButtonToCell];
}
相关问题