如何将UITableView添加到基于视图的应用程序中,其中用户将点击多个单元格,该单元格将变为选中状态,就像时钟应用程序名为"Repeat“(Clock>Alarms> + >Repeat)的”新闹钟“设置一样,以及如何获取数组中所有选定的单元格?
发布于 2010-06-15 05:31:09
在您的-tableView:didSelectRowAtIndexPath:实现中,您将根据当前值设置表格视图单元格的accessoryType属性(因此,它可以通过多次点击来打开和关闭)。例如:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)path {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:path];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
} else {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
}除了单元格自己的附件类型状态之外,您还可以维护一个选定状态数组,或者遍历表视图中的单元格,查询每个单元格的状态,以便读出选定的行。
发布于 2012-12-12 04:27:55
对于多个选择,在viewDidLoad()中添加以下行
tableView.allowsMultipleSelection = true在tableView(_:cellForRowAt:)中将每个cell出队(或初始化)后对其进行配置
let selectedIndexPaths = tableView.indexPathsForSelectedRows
let rowIsSelected = selectedIndexPaths != nil && selectedIndexPaths!.contains(indexPath)
cell.accessoryType = rowIsSelected ? .checkmark : .none
// cell.accessoryView.hidden = !rowIsSelected // if using a custom image在选中/取消选中时更新每个单元格
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)!
cell.accessoryType = .checkmark
// cell.accessoryView.hidden = false // if using a custom image
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)!
cell.accessoryType = .none
// cell.accessoryView.hidden = true // if using a custom image
}完成后,获取所有选定行的数组
let selectedRows = tableView.indexPathsForSelectedRows并获取所选数据,其中dataArray映射到只有一个部分的表视图中的行
let selectedData = selectedRows?.map { dataArray[$0.row].ID }发布于 2013-05-29 22:26:04
@BrendanBreg implementation对我不起作用。@RaphaelOliveira提供了good solution,但是当你向下滚动表格时-错误的行被选中(因为UITableView缓存了它的单元格)。所以,我稍微修改了拉斐尔的解决方案:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryNone;
}
/*Here is modified part*/
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
/*
...
Your implementation stays here
we're just adding few lines to make sure
that only correct rows will be selected
*/
if([[tableView indexPathsForSelectedRows] containsObject:indexPath]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
}https://stackoverflow.com/questions/3040894
复制相似问题