如何创建一个包含单个UIButton占用单元格大部分空间的UITableViewCell?

问题描述

| 我正在尝试创建一个包含单个大按钮的UITableViewCell。 我尝试了看似很明显的事情,将UIButton添加到单元格的contentView中,但是没有用(单元格显示为空)。我在做什么错?
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@\"startButtonCell\"];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                   reuseIdentifier:@\"startButtonCell\"] autorelease];
    UIButton *btn = [[UIButton alloc] initWithFrame:cell.contentView.bounds];
    [cell.contentView addSubview:btn];
    if (!self.task.isCompleted) {
        btn.titleLabel.text = @\"Start!\";
    }else{
        btn.titleLabel.text = @\"Continue!\";
    }
    [btn release];
}
    

解决方法

请尝试以下操作:
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setFrame:cell.contentView.frame];
[btn setTitle:@\"Button Title\" forState:UIControlStateNormal];
[cell.contentView addSubview:btn];
我到目前为止还不是专家,但是我认为您的解决方案存在的问题是,默认情况下,UIButton的按钮样式为UIButtonTypeCustom,这是不可见的,因为尚未进行自定义。如果我从上面更改代码
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
我得到与您相同的结果。没有可见的按钮。如果要使用UIButtonTypeCustom,则需要进行一些自定义。例如,将背景图像添加到您的按钮。