ios 如何以编程方式在 Swift 中的 UITableView 中选择一行

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

How to programmatically select a row in UITableView in Swift

iosswiftuitableview

提问by Mikee

I need to select a row in a UITableView programmatically using Swift 1.2.

我需要使用 Swift 1.2 以编程方式在 UITableView 中选择一行。

This is the simple code:

这是简单的代码:

var index = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.selectRowAtIndexPath(index, animated: true, scrollPosition: UITableViewScrollPosition.Middle)
self.tableView(self.tableView, didSelectRowAtIndexPath: index)

The above gives me the following error:

以上给了我以下错误:

Cannot invoke 'selectRowAtIndexPath' with an argument list of type '(NSIndexPath!, animated: Bool, scrollPosition: UITableViewScrollPosition)'

无法使用类型为“(NSIndexPath!,动画:布尔,scrollPosition:UITableViewScrollPosition)”的参数列表调用“selectRowAtIndexPath”

What is wrong with my Swift 1.2 code?

我的 Swift 1.2 代码有什么问题?

My UItableView has been created in IB in the UIViewController that I am trying to call the code above. When I put the code in a UITableViewController the compiler does not give any errors. Do I need to embed a UITableViewController in a container or is there another way?

我的 UItableView 已在 IB 中的 UIViewController 中创建,我试图调用上面的代码。当我将代码放在 UITableViewController 中时,编译器不会给出任何错误。我需要在容器中嵌入 UITableViewController 还是有其他方法?

采纳答案by Martin R

The statement

该声明

self.tableView.selectRowAtIndexPath(index, animated: true, scrollPosition: UITableViewScrollPosition.Middle)

assumes that tableViewis a property of the view controller, connected to a table view in the Storyboard. A UITableViewController, for example, already has this property.

假设这tableView是视图控制器的一个属性,连接到故事板中的表视图。UITableViewController例如,A已经具有此属性。

In your case, the view controller is a not a table view controller but a subclass of a UIViewController. It also has an outlet that is connected to the table view, but it is not called tableViewbut menuTable. Then of course you have to call

在您的情况下,视图控制器不是表视图控制器,而是UIViewController. 它还有一个连接到 table view 的 outlet,但它不叫 tableViewbut menuTable。那么当然你必须打电话

self.menuTable.selectRowAtIndexPath(index, animated: true, scrollPosition: UITableViewScrollPosition.Middle)

to select a row of that table view.

选择该表视图的一行。

The strange error messages are caused by the fact that self.tableViewcan also be understood by the compiler as a "curried function" (compare http://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/).

奇怪的错误信息是由self.tableView编译器也可以理解为“柯里化函数”的事实引起的 (比较http://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/) .

回答by Sourabh Sharma

Swift 3.x Solution

Swift 3.x 解决方案

Selecting a Row

选择一行

let indexPath = IndexPath(row: 0, section: 0)
myTableView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom)
myTableView.delegate?.tableView!(myTableView, didSelectRowAt: indexPath)

DeSelecting a Row

取消选择行

let deselectIndexPath = IndexPath(row: 7, section: 0)
myTableView.deselectRow(at: deselectIndexPath, animated: true)
myTableView.delegate?.tableView!(myTableView, didDeselectRowAt: indexPath)

回答by Pankaj purohit

Use below code,after loading your table view with data:

在使用数据加载表视图后,使用以下代码:

let rowToSelect:NSIndexPath = NSIndexPath(forRow: 0, inSection: 0);  //slecting 0th row with 0th section
self.tableView.selectRowAtIndexPath(rowToSelect, animated: true, scrollPosition: UITableViewScrollPosition.None);

now,you have to manually call didSelectRowAtIndexPath:delegate method using below code:

现在,您必须使用以下代码手动调用didSelectRowAtIndexPath:委托方法:

self.tableView(self.tableView, didSelectRowAtIndexPath: rowToSelect); //Manually trigger the row to select

Thanks.

谢谢。

回答by Sandu

Swift 3.x

斯威夫特 3.x

if you want to do it at the 'cell-creation', you can do it like this

如果你想在“细胞创建”中做到这一点,你可以这样做

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = TableViewCell()
    let item = items[indexPath.row]

    cell.textLabel?.text    = item.title

    if (item.checked) {
        tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
    }

    return cell
}

回答by Alessandro Ornano

Using Swift 2.x, as described by Pankaj purohit answersthe correct method is:

使用Swift 2.x,如Pankaj purohit所述,正确的方法是:

func tapRowAtIndex(index:Int) {
        let rowToSelect:NSIndexPath = NSIndexPath(forRow: index, inSection: 0)
        self.tableView.selectRowAtIndexPath(rowToSelect, animated: true, scrollPosition: UITableViewScrollPosition.None)
        self.tableView(self.tableView, didSelectRowAtIndexPath: rowToSelect)
}

Keep in mind that if you call this method from an external class for example, you dont know when tableView has finished its loading, so what's the possibilities?, how to workaround this problem? :

请记住,例如,如果您从外部类调用此方法,您不知道 tableView 何时完成加载,那么有什么可能性?,如何解决此问题?:

Step one: create a class boolean var

第一步:创建一个类布尔变量

var automatingTap: Bool = false

Step two: check when the table finish its loading and launch an "end operations" method:

第二步:检查表何时完成加载并启动“结束操作”方法:

func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) 
{
    let lastRowIndex = tableView.numberOfRowsInSection(0)
    if indexPath.row == lastRowIndex - 1 {
       endOperations()
    }
}

func endOperations() 
{
   print("finished loading")
   if automatingTap {
        tapRowAtIndex(0)
        automatingTap = false
   }
}

Step three: call my tableView class from another class

第三步:从另一个类调用我的 tableView 类

for example:

例如:

override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
    if segue!.identifier == "DetailsTableView" {
        let viewController:ViewController = segue!.destinationViewController as ViewController
        viewController.automatingTap = true
    }
}

回答by blacker

This reusable function works and validate the size of table.

这个可重用的函数可以工作并验证表的大小。

func selectRow(tableView: UITableView, position: Int) {
    let sizeTable = tableView.numberOfRows(inSection: 0)
    guard position >= 0 && position < sizeTable else { return }
    let indexPath = IndexPath(row: position, section: 0)
    tableView.selectRow(at: indexPath, animated: true, scrollPosition: .middle)
}

you can use it in this way

你可以这样使用它

selectRow(tableView: myTableView, position: pos)

or you can implement this extension:

或者你可以实现这个扩展:

extension UITableView {
    func selectRow(row: Int, section: Int = 0) {
        let sizeTable = self.numberOfRows(inSection: section)
        guard row >= 0 && row < sizeTable else { return }
        let indexPath = IndexPath(row: row, section: section)
        self.selectRow(at: indexPath, animated: true, scrollPosition: .middle)
    }
}

and you can use it in this way:

你可以这样使用它:

mytableView.selectRow(row: pos, section: 0)

or

或者

mytableView.selectRow(row: pos)

回答by rip...

Swift 4.2:

斯威夫特 4.2

Select one or more Rows

选择一行或多行

let ndx:IndexSet = [1]
// or:  let ndx:IndexSet = [1, 2, 3]; // etc
tableview?.selectRowIndexes(ndx, byExtendingSelection: false);

Deselect a Single Row

取消选择单行

tableview?.deselectRow(current)

Note that if you have (func tableViewSelectionDidChange(...)) implemented, that will be triggered by the above.

请注意,如果您已实现 ( func tableViewSelectionDidChange(...)),则会由上述内容触发。

Also see Charlton Provatas' answer at https://stackoverflow.com/a/48696458/352920for an extension to NSTableView, that provides a simple

另请参阅 Charlton Provatas 在https://stackoverflow.com/a/48696458/352920 上的回答,了解 NSTableView 的扩展,它提供了一个简单的

tableview?.selectRow(at:)