UITableView DidSelectRowAtIndexPath?
我有几个项目(所有文本)的表格视图。 当用户单击该行时,我希望将该单元格中的文本添加到数组中。
我如何将文本从单元格中取出?
我已经有了:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { }
有一个简单的线我可以用来抓住用户点击单元格的文本?
使用UITableView
的cellForRowAtIndexPath:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; NSString *cellText = cell.textLabel.text; }
这与你在cellForRowAtIndexPath中做的相反。
[myArray addObject: [datasource objectAtIndex:indexPath.row]];
一般来说,你可以在Apple文档中find这样的问题的答案。 对于这种情况,请查看UITableView类参考 ,您将看到一个部分标题:访问单元格和部分。 这给你以下方法:
– cellForRowAtIndexPath:
现在使用它来访问单元格,然后使用从单元格中获取文本(如果您不确定如何,请查看UITableViewCell类参考 。
总之,你的方法可能看起来像这样:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; NSString *cellText = cell.textLabel.text; [myArray addObject:cellText]; }
我第一次猜测会得到索引,[indexPath行]; 然后从数据源(数组或核心数据)中获取数据,而不是直接从表本身获取数据。
Swift版本:
let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)! let cellText: String = cell.textLabel.text