ios 如何在 Swift 中获取选定行的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28672836/
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-31 04:56:31  来源:igfitidea点击:

How to get a value of selected row in Swift?

iosswifttableview

提问by ?lkin Elimov

I have a Table View Controller in my swift application. How to I get a value of selected row (cell)?
For example, I want to show a value of selected row with alert when the user clicked on row.

我的 swift 应用程序中有一个表视图控制器。如何获取选定行(单元格)的值?
例如,我想在用户单击行时显示带有警报的选定行的值。

回答by dehlen

Just implement the method:

只需实现该方法:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var alert = UIAlertView()
    alert.delegate = self
    alert.title = "Selected Row"
    alert.message = "You selected row \(indexPath.row)"
    alert.addButtonWithTitle("OK")
    alert.show()
}

This delegate method gets fired whenever you select a row. Via NSIndexPathyou get the exact sectionand rowthe user selected. In order to make sure the method gets called you need to make sure your tableview's delegateis set.

每当您选择一行时,就会触发此委托方法。通过NSIndexPath你得到确切的sectionrow用户选择的。为了确保该方法被调用,您需要确保您的 tableviewdelegate已设置。

But since you are using an UITableViewControllerthis should already be done automatically for you.

但是由于您使用的是 ,UITableViewController这应该已经为您自动完成了。

For further documentation see: tableView:didSelectRowAtIndexPath

有关更多文档,请参阅:tableView:didSelectRowAtIndexPath

回答by Ugur Atci

   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        var selectedItem = indexPath  
        print (selectedItem.row) 
    }

You can handle this method SWIFT 3.0 Code

您可以通过SWIFT 3.0 代码处理此方法

回答by Dharmesh Kheni

Use this function for it:

为此使用此功能:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
 NSLog("You selected cell #\(indexPath.row)!")
}

回答by Dmitry

Swift 4:

斯威夫特 4:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    ...
}