我是Objective-c编码的新手。我试图在表视图控制器上实现一个复选标记。我希望当我单击一个单元格时看到复选标记,而当我重新单击该单元格时消失。
例如,我在下面找到了此代码。但是我不清楚一件事。“数据”和“检查数据”是什么意思?我们必须在代码之前设置它们吗?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// do usual stuff here including getting the cell
// determine the data from the IndexPath.row
if (data == self.checkedData)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell; }
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// determine the selected data from the IndexPath.row
if (data != self.checkedData) {
self.checkedData = data;
}
[tableView reloadData]; }
所以我在搜索一些代码,但找不到我想要的任何代码。
我会很高兴为您提供任何帮助。
谢谢。
您发布的代码不适合一般用途。为了支持多个单元格选择,您需要一个额外的数据结构(例如boolean数组或NSIndexSet
)来跟踪所选索引。然后,一旦获得tableView:didSelectRowAtindexPath:
更新,数据结构并强制重新加载表,即[self.tableView reloadData]
为了显示/隐藏选择复选标记
一些代码块
@implementation TableViewController {
NSArray * _data;
NSMutableIndexSet *_selectedIndexes;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
...
self.selectedIndexes = [[NSMutableIndexSet alloc] init];
...
return self;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([_selectedIndexes containsIndex:indexPath.row]) {
[_selectedIndexes removeIndex:indexPath.row];
} else {
[_selectedIndexes addIndex:indexPath.row];
}
[tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
....
if ([_selectedIndexes containsIndex:indexPath.row])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
...
return cell;
}
请注意,它NSMutableIdexSet
必须具有与NSArray
用来填充tableView单元格的数据结构相同的长度。另外,正如我所说,您可以使用BOOL数组。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句