如何在 uitableviewcell 上创建带有取消按钮的复选标记?

问题描述 投票:0回答:2

我不是 Objective-C 的初学者,但对 UITableViewCell 相当新手。

我试图让用户能够通过按下按钮在 TableViewCell 上创建复选标记。这是我想出的代码,

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

    UITableViewCell *cellx = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];


    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(40, 5, 40, 40)];
    [button setTitle:@"Button" forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor greenColor]];
    [button setTintColor:[UIColor redColor]];
    [button setTag:indexPath.row];
    [cellx addSubview:button];
    [cellx setIndentationLevel:1];
    [cellx setIndentationWidth:45];

    if (button.touchInside == YES)
    {
        NSLog(@"Button Pressed");
        cellx.accessoryType = UITableViewCellAccessoryCheckmark;
        [tableView reloadData];
    }

    return cellx;
}

该代码似乎对我不起作用。

有什么想法吗?

ios objective-c uitableview
2个回答
1
投票

试试这个:

@interface TableViewController ()

@property (strong, nonatomic) NSMutableArray *selectedIndexPaths;

@end

@implementation TableViewController

- (NSMutableArray *)selectedIndexPaths {
  if (!_selectedIndexPaths) {
    _selectedIndexPaths = [NSMutableArray array];
  }
  return _selectedIndexPaths;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return 20;
}

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

  if ([self.selectedIndexPaths containsObject:indexPath]) {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
  } else {
    cell.accessoryType = UITableViewCellAccessoryNone;
  }

  return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  if ([self.selectedIndexPaths containsObject:indexPath]) {
    [self.selectedIndexPaths removeObject:indexPath];
    [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone;
  } else {
    [self.selectedIndexPaths addObject:indexPath];
    [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
  }
  [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

1
投票

效果更好的策略是:

  • 创建
    UITableViewCell
    的自定义子类并构建其接口 在 IB 中,所以加载时按钮就在那里
  • 保留对象数组 其中每个对象代表您想要在一个单元格中显示的内容
  • 当点击按钮时,告诉你的控制器更新匹配的数组对象来表达它 应该检查一下
  • 告诉您的表视图重新加载数据,无论是完全加载还是针对更改的索引路径加载
  • cellForRowAtIndexPath
    中,只需将按钮更新为 是否选中取决于匹配的数组项。
© www.soinside.com 2019 - 2024. All rights reserved.