向TableView单元格添加一个按钮:

时间:2012-01-30 16:02:42

标签: iphone uitableview uibutton

我有一个UI tableView,我正在尝试创建一个像Safari设置中用来清除历史记录的按钮:

enter image description here

我尝试的代码并没有真正起作用,我确信有更好的方法:

        case(2):
           // cell = [[[ButtonLikeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];


            if (indexPath.row == 0) 
            {            
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                [button setFrame:cell.bounds]; 
                [button addTarget:self action:@selector(clearButtonClick) forControlEvents:UIControlEventTouchUpInside];
                [button setBackgroundColor:[UIColor purpleColor]];
                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [button setTitle:@"Clear Data" forState:UIControlStateNormal];
                cell.accessoryView = nil;
                cell.clipsToBounds=YES;
                [cell.contentView addSubview:button];
            }

            break;
    }
}

return(cell);

}

2 个答案:

答案 0 :(得分:4)

tableview单元格上的子类对此有些过分,基本上你需要做的就是将textLabel的文本对齐设置为中心

case(2):
        if (indexPath.row == 0) 
        {   
            cell.textLabel.textAlignment = UITextAlignmentCenter;
        }
        break;

答案 1 :(得分:2)

无需使用实际的UIButton。

行和“正常”行之间的唯一区别是标签的位置。 子类UITableViewCell并覆盖-laysubviews以使标签居中,您已完成,如下所示:

@interface ButtonLikeCell : UITableViewCell

@end

@implementation ButtonLikeCell

-(void)layoutSubviews
{
    self.titleLabel.center = self.center;
}

@end

这将重新定位单元格的标签,使其看起来与您正在寻找的类似。

相关问题