HIII, 我想制作一个tableview,当我点击单元格时,它将进入下一个视图,我可以选择一个特定的选项(一次只有一个)带有复选标记和所选选项中的任何文本它应该在前一个视图中显示(也是一个表格视图)
请帮我解决这个问题。
使用下面的方法时,它会选择我正在点击的所有选项,但我想只有一个单元格会有我点击的复选标记。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
}
提前致谢
答案 0 :(得分:2)
答案 1 :(得分:0)
您可以跟踪类型NSIndexPath
的类属性中当前选定的项目。首先将此属性初始化为nil
或之前选择的任何值。您还可以修复cellForRowAtIndexPath
以将单元格的indexPath与“当前选定的”索引路径属性进行比较,并在匹配时在其中添加复选标记。现在您在didSelectRowAtIndexPath
中所要做的就是这样(代码未经编译器检查,可能会导致小错误):
NSIndexPath *oldIndexPath = self.selectedIndexPath; // retain this if not using ARC!
self.selectedIndexPath = indexPath; // passed in from didSelectRowAtIndexPath
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects: oldIndexPath, self.selectedIndexPath, nil], UITableViewRowAnimationNone];
// release oldIndexpath if noct using ARC
由于cellForRowAtIndexPath
应根据self.selectedIndexPath
创建带或不带复选标记的单元格,这将相应地更新单元格(如果已经选择了某些内容,还会在开头创建正确的视图)。 / p>
奖励:您有self.selectedIndexPath
可用于确定您应该返回“调用”视图的内容,即选择了哪一行。
答案 2 :(得分:0)
让我们使用A和B来表示您的第一个表视图和第二个表视图。并且说你可以从A导航到B.
你将需要这些东西:
您的uitableview单元格所代表的自定义对象,或NSIndexPath,甚至是用作A的索引的整数。设置A的值 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {},因为稍后您在B中进行了选择后,您想知道将文本追加到哪里。
在B中显示复选标记 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {},将其设置为当前选定的一个。你必须想办法记录信息,这应该来自你从A到B的导航过程。我通常做的是创建一个B的自定义初始化函数,从A调用。你也可以创建一个当前选中的对象B中的属性,并在从A导航之前从A开始设置。无论你做什么,你都可能想要创建该属性。
创建一个B的委托,实现一个函数 - (void)getSelectionFromB:(SomeClass *)obj {}和B的内部 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {},调用[delegate getSelectionFromB:selectedObject],你应该没事。
在A的实现 - (void)getSelectionFromB:(SomeClass *)obj {}中,要么在tableview中找到单元格并进行更改,要么更改NSArray或用于填充表格视图的任何内容,以及然后重新加载数据。
希望这有帮助。
答案 3 :(得分:0)
只需以这种方式一起使用tableView:didSelectRowAtIndexPath
和tableView:cellForRowAtIndexPath
方法:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
}
而且,如果你不想让你的用户看到仍然突出显示单元格的坏视线,只需在结束括号之前添加这行代码:
[tableView deselectRowAtIndexPath:indexPath animated:YES];
P.S。我制作动画只是为了让它看起来很好。
参考文献: