Search code examples
macosswiftnstableview

Pre-selecting row in NSTableView not working


I am using the code below in viewDidLoad() to try and pre-select a table row in a tableView object (tblProjectNumber). No errors at compile or run time.

Everything loads ok and I can select table rows by a mouse click without any problems once the view is loaded. However, I cannot load the view with the required default row pre-selected. I have tried the following code in viewDidLoad() (the last three lines refer). The tableView does not show a selected row and does not scroll the row at index(100) when the data loads.

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.wantsLayer = true
    self.view.layer?.backgroundColor = NSColor.windowBackgroundColor().CGColor
    self.view.window?.title = "Project Detail Module"
    self.view.window?.titleVisibility

    // sort the list of project numbers so that they display correctly when the view is first loaded
    self.sortProjectNumberArray()
    self.loadProjectRowDataArray()
    self.sortPPRFilesForLatestDate()

    // pre-select table row to load on initial display of the tableView
    let index = NSIndexSet(index: 100)
    self.tblProjectNumber.scrollRowToVisible(100)
    self.tblProjectNumber.selectRowIndexes(index, byExtendingSelection: true)
}

The answeres here:

have helped but I haven't been able to solve the issue. Also the call to selectRowAtIndexPath used in the last link doesn't seem to be available in Swift so it doesn't work for me either.


Solution

  • Try your code inside tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? method.

    Don't know which select method will work in OSX but selectRowAtIndexPath is the correct method for iOS. So try every possible selectIndex method of OSX but inside the viewForTableColumn method through which the tabledata is actully being displayed. i.e. while displaying tabledata..it will check for the index you want to be selected.

    Hope this may help !