【问题标题】:Adding buttons to a UITableView cell将按钮添加到 UITableView 单元格
【发布时间】:2015-04-10 06:42:31
【问题描述】:

我正在尝试向我的 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)]

【问题讨论】:

    标签: ios xcode uitableview uibutton


    【解决方案1】:

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

    [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];
    

    只有一种可能的方式,但速度很快

    【讨论】:

    • 不走运,按钮仍然没有出现
    • 设置断点或在UIButton *button = self.buttons[0]; 之后使用NSLog(@"myButton: %@", button) 确保按钮对象没有损坏或大小为0,有样式等等。对于测试用例,设置背景色
    • 好吧,那是因为我没有正确初始化我的数组。现在应用程序崩溃了,因为我尝试访问尚未填充的数组(它正在使用 Parse.com 进行后台工作,检索图像)。有没有办法延迟 tableView cellForRowAtIndexPath?
    • 非常感谢!真的很简单!现在完美运行。担心我将不得不做一些复杂的事情,比如排队任务。再次感谢
    【解决方案2】:

    在你的 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    中试试这个
    if ([cell.contentView viewWithTag:100] == nil) {
            button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            button.frame = CGRectMake(130,25, 40.0, 40.0);
            [button setTitle:@"+" forState:UIControlStateNormal];
            [button addTarget:self action:@selector(aMethod:)
             forControlEvents:UIControlEventTouchUpInside];
            button.tag=100;
            [cell.contentView addSubview:button];
        }
    

    然后执行操作

    -(void)aMethod:(id)sender {
        NSInteger tag=[[sender superview] tag];
        //NSInteger value=[[self.qtt objectAtIndex:tag] integerValue]+1;
        //[self.qtt replaceObjectAtIndex:tag withObject:[@(value) stringValue]];
        //[self.mytableview reloadData];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多