Scroll down the UITableViewCell and select it.

I currently have the following setting: UITableView

which results in (when the user selects a cell) to UIPageViewController

, so the user can scroll through the same items presented in UITableView

, without constantly going back and selecting another item.

When the user comes back, I want to scroll to the last viewed item in UIPageViewController

and highlight it so the user knows better where they are.

Using tableView:scrollToRowAtIndexPath:atScrollPosition:animated:

, I can scroll to the last viewed cell, and with tableView:selectRowAtIndexPath:animated:scrollPosition:

and tableView:deselectRowAtIndexPath:animated

I can select the cell. But I haven't figured out a good, clean way to do it at the same time, i.e. first scroll and then select a cell.

Here is my current working but hacky solution that could break:

if let visible = tableView.indexPathsForVisibleRows {
    if !visible.contains(indexPath) {
        // cell is not visible, scroll required
        tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Middle, animated: true)
        // highlight the cell after 0.4 seconds (aka somewhat after the scroll animation)
        let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_SEC)))
        dispatch_after(delayTime, dispatch_get_main_queue()) {
            self.tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: .None)
            self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
        }
    } else {
        // no need to scroll, just highlight
        tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: .None)
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
}

      

Is there a better way to do this without relying on hardcoded time?

+3


source to share





All Articles