How to programmatically select a row in UITableView in Swift

前端 未结 7 559
执笔经年
执笔经年 2020-12-24 04:52

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

This is the simple code:

var index = NSIndexPath(forRow: 0, inSection: 0)
         


        
7条回答
  •  囚心锁ツ
    2020-12-24 05:14

    The statement

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

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

    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 tableView but menuTable. Then of course you have to call

    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.tableView can also be understood by the compiler as a "curried function" (compare http://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/).

提交回复
热议问题