我不是 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;
}
该代码似乎对我不起作用。
有什么想法吗?
试试这个:
@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];
}
效果更好的策略是:
UITableViewCell
的自定义子类并构建其接口
在 IB 中,所以加载时按钮就在那里cellForRowAtIndexPath
中,只需将按钮更新为
是否选中取决于匹配的数组项。