Async-
Async-

Reputation: 3289

Can not scroll to row at index path in UITableView

I am trying to scroll to index path when I click on collection view cell in a different view, with the help of observer pattern with notification, and get exception that my bound for row and section are 0 (while the table IS populated properly).

func selectedDay(notification: NSNotification) {
    let userInfo = notification.userInfo as! [String: AnyObject]
    let selectedDayIndex = userInfo["selectedDayIndex"] as! Int?

    if let selectedDay = selectedDayIndex {
        print("YES: \(selectedDay)")
        self.tableView.reloadData()
        self.scrollToRow(selectedDay)
        }
}


func scrollToRow(section: Int) {
    let indexPath = NSIndexPath(forRow: 0, inSection: section)
    self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Middle, animated: true)
}

I am able to print the index I am getting from the notification, and my table is populated like this: enter image description here

I understand that my table seems to be empty, when accessing it from this method. I do have proper delegate, data source connections. This is my log: enter image description here

cell for row at index is loaded from the array, that is fetched with completion block, and table.reloadData() on return of boolean true: enter image description here

Upvotes: 0

Views: 560

Answers (2)

beyowulf
beyowulf

Reputation: 15321

This line:

let indexPath = NSIndexPath(forRow: 0, inSection: section)

assumes there is an object at meetings[0][section]. You should say:

func scrollToRow(section: Int) {
if(meetings.count > 0 && meetings[section].count > 0)
{
    let indexPath = NSIndexPath(forRow: 0, inSection: section)
    self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true)
}else{
    print("there is no section: \(section)")
}

}

Upvotes: 1

Async-
Async-

Reputation: 3289

Ok, just simple check helped, because indeed some of the sections were not populated:

func scrollToRow(section: Int) {
    if(meetings.count > 0 && meetings[section].count > 0)
    {
        let indexPath = NSIndexPath(forRow: 0, inSection: section)
        self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true)
    }else{
        print("there is no section: \(section)")
    }
}

Upvotes: 0

Related Questions