如何创建一个 UITableViewCell 包含一个 UIButton 占用大部分单元格的空间?
Posted
技术标签:
【中文标题】如何创建一个 UITableViewCell 包含一个 UIButton 占用大部分单元格的空间?【英文标题】:How to create a UITableViewCell that contains a single UIButton taking up most of the cell's space? 【发布时间】: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:
吗?
【参考方案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,您必须进行一些自定义。例如,为您的按钮添加背景图片。
【讨论】:
以上是关于如何创建一个 UITableViewCell 包含一个 UIButton 占用大部分单元格的空间?的主要内容,如果未能解决你的问题,请参考以下文章
如何将 UITableViewCell 中的 UITextView 滚动到键盘顶部?
如何清除包含在重复使用的自定义 UITableViewCell 中的 WKWebview?
如何以编程方式快速向 UITableViewCell 内的 UIStackView 添加约束?
如何检查 UITableViewCell 是不是包含 UIView