ios - 将按钮添加到 UITableView 单元格

标签 ios xcode uitableview uibutton

我正在尝试使用如下代码向我的 UITableView 单元格添加按钮:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    UIButton *button = self.buttons[0];
    [cell addSubview:button];

    return cell;
}

虽然按钮没有显示。是否可以像这样向单元格添加按钮,或者我是否必须制作自定义 UITableViewCell 类?

当为数组制作按钮时,框架设置如下:

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 70, 70)]

最佳答案

添加元素的用法在某些时候发生了变化。使用

[cell.contentView addSubview:button];

并且如果已经添加了按钮,请不要忘记在之前进行验证 :P

enum
{
    kButtonForA = 3333 // example
};

对于每个按钮集

button.tag = kButtonForA;

并使用它们

UIButton* btn = (UIButton *)[cell.contentView viewWithTag:kButtonForA];
if(!button)
    btn = self.buttons[i];

更新

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(!self.buttons || [self.buttons count] == 0)
        return 0;
    return ...;
}

在你初始化你的数组之后,使用

[tableView reloadData];

只是一种可能的方式,但是一种快速的方式

关于ios - 将按钮添加到 UITableView 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28428185/

相关文章:

ios - UIViewController 如何自动遵守 TableView 协议(protocol)?

objective-c - 如何从同一个 NIB(源于 UITabController)加载 UIView?

ios - 在 iOS 中选择适当的多线程技术

ios - UITextField 不响应 iOS8 中的触摸?

ios - errSecInternalComponent 命令 CodeSign 失败,退出代码为 65

ios - 如何使自动取消选择tableview单元格

ios 当我添加第二个应用程序时,是否需要添加第二个应用程序的证书?

ios - 如何在 Xcode 调试器中记录类名

iphone - 如何获取数组中某一项的索引

ios - 一直向下滚动到 UITableView 的底部