ios UITableView DidSelectRowAtIndexPath?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8404922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:46:00  来源:igfitidea点击:

UITableView DidSelectRowAtIndexPath?

iphoneobjective-ciosxcodeipad

提问by user964627

I have a table view with a few items (all text). When the user clicks the row I want that text in that cell to be added to an array.

我有一个包含几个项目(所有文本)的表格视图。当用户单击该行时,我希望将该单元格中的文本添加到数组中。

How Do I grab the text out of the cell?

如何从单元格中提取文本?

I already Have:

我已经有了:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

}

Is there a simple line I can use to grab the text out the cell that the user clicks?

是否有一条简单的行可以用来从用户单击的单元格中提取文本?

回答by Joe

Use UITableView's cellForRowAtIndexPath:

使用UITableViewcellForRowAtIndexPath:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSString *cellText = cell.textLabel.text;
}

回答by Rayfleck

It's the inverse of what you did in cellForRowAtIndexPath.

这与您在 cellForRowAtIndexPath 中所做的相反。

 [myArray addObject: [datasource objectAtIndex:indexPath.row]];

回答by PengOne

In general, you can find most answers to questions like this in the Apple documentation. For this case, look under UITableView Class Referenceand you will see a section header: Accessing Cells and Sections. This give you the following method:

一般来说,您可以在 Apple 文档中找到此类问题的大部分答案。对于这种情况,查看UITableView 类参考下,您将看到一个部分标题:访问单元格和部分。这为您提供了以下方法:

– cellForRowAtIndexPath:

Now use this to access the cell, and then use get the text from the cell (if you're unsure how, look under the UITableViewCell Class Reference.

现在使用它来访问单元格,然后使用从单元格中获取文本(如果您不确定如何,请查看UITableViewCell Class Reference

All together, your method might look something like this:

总之,您的方法可能如下所示:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSString *cellText = cell.textLabel.text;
    [myArray addObject:cellText];
}

回答by Antwan van Houdt

My first guess would be getting the index, [indexPath row]; then fetching the data from your datasource ( an array or core data ) rather than directly from the table itself.

我的第一个猜测是获取索引,[indexPath row]; 然后从您的数据源(数组或核心数据)而不是直接从表本身获取数据。

回答by Gleb Karpushkin

Swift Version:

迅捷版:

let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
let cellText: String = cell.textLabel.text