Showing posts with label NSViewController. Show all posts
Showing posts with label NSViewController. Show all posts

Thursday, October 18, 2018

UIKit protocol of the month: StoryboardInstantiatableViewController

Github Gist.

I want to share this little invention with the community. I use it for the last month and find it notably helpful: protocol StoryboardInstantiatableViewController { static var storyboardId: String { get } } extension StoryboardInstantiatableViewController where Self: UIViewController { static func instantiate(from storyboard: UIStoryboard?) -> Self? { return storyboard?.instantiateViewController(withIdentifier: Self.storyboardId) as? Self } }
This protocol along with the extension provides some syntactic sugar and solves two common problems:
  • Shortens the instantiation
  • Answers, where to store the storyboard id

Usage example:

// Declaration: class TaskViewController: UIViewController, StoryboardInstantiatableViewController { // The same id as specified in Identity inspector static let storyboardId: String = "task" // ... } // Initializing from Storyboard: // ... guard let taskVC = TaskViewController.instantiate(from: storyboard) else { return } navigationController?.pushViewController(taskVC, animated: true)

Update:

Surprisingly, I bumped into another similar protocol, named StoryboardInstantiatable. The main difference that it's designed for use with NSViewController and Cocoa instead of Cocoa Touch. The fact is, that the gist was posted 5 months earlier than this blog post. So Satori Maru is the first one who invented the idea, although I came to it independently.

How to Record Calls on iPhone