【问题标题】:How to create a UITableViewCell that contains a single UIButton taking up most of the cell's space?如何创建一个 UITableViewCell 包含一个 UIButton 占用大部分单元格的空间?
【发布时间】:2011-05-26 14:41:28
【问题描述】:

我正在尝试创建一个包含单个大按钮的 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];
}

【问题讨论】:

  • 我假设这是您的-cellForRowAtIndexPath: 实现...您确定您的代码执行超过if (cell == nil) { 吗?按钮的大小是否正确创建?你能提供完整的-cellForRowAtIndexPath:吗?

标签: cocoa-touch uitableview uibutton


【解决方案1】:

尝试以下方法:

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,您必须进行一些自定义。例如,为您的按钮添加背景图片。

【讨论】:

    猜你喜欢
    • 2023-01-21
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多