Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions iOSDevUK/Controllers/Sessions/ProgrammeTableViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ class ProgrammeTableViewController: UIViewController, UITableViewDelegate, UITab

var selectedSessionItem: SessionItem?

var shouldScrollToCurrent: Bool = true

// MARK: - Lifecycle

override func viewDidLoad() {
Expand All @@ -43,6 +45,16 @@ class ProgrammeTableViewController: UIViewController, UITableViewDelegate, UITab
super.didReceiveMemoryWarning()
}

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

if shouldScrollToCurrent {
// We'd rather not animate, but how can we know when the table view knows the correct
// size for all the cells in order to scroll to the right place, before the view appears?
scrollToCurrentSession(animated: true)
}
}

// MARK: - Data Initialisation

func accessDayList(withContext context: NSManagedObjectContext) -> [Day] {
Expand Down Expand Up @@ -86,6 +98,30 @@ class ProgrammeTableViewController: UIViewController, UITableViewDelegate, UITab
}
}

/// Find the current or next session for the current set of sessions and scroll to it.
func scrollToCurrentSession(animated: Bool) {
guard let fetchedResultsController = fetchedResultsController else {
return
}

/// Find the session in the already-fetched results
let nextOrCurrentSession = fetchedResultsController.fetchedObjects?.first { session in
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just noticed that the Session object already has a way to calculate the current and the next Session. Maybe you can use Session.nowSession(forDate:) and Session.nextSession(forDate:) here instead of reimplementing it?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I saw those too, but it seems like a silly idea to run 2 Core Data queries to find this?

guard let endTime = session.endTime else {
return false
}
return endTime.timeIntervalSinceNow > 0
}

/// If we found one, resolve it to a section index and row
if let sessionToScrollTo = nextOrCurrentSession {
if let indexPathOfSessionToScrollTo = fetchedResultsController.indexPath(forObject: sessionToScrollTo) {
tableView.scrollToRow(at: indexPathOfSessionToScrollTo, at: .top, animated: animated)
}
}

shouldScrollToCurrent = false
}

// MARK: - Segmented Control

func setupSegmentedControlWithDays(_ days: [Day]) {
Expand Down