Use IBSegueAction To Make Storyboards Less Awful
Use initializers
--
It’s always good to make code better. If your codebase is using property injection I’d say it would be great to get rid of that and start using initialisers.
Since Xcode 11 we’ve been able to to do this using @IBSegueAction
, but I noticed there are some guides saying you can’t mix using @IBSegueAction
and ordinary segues (not true). So I thought I’d make an article about how they can be used and combined in a project!
I then made a repo for this so people could see the code: https://github.com/stevencurtis/SwiftCoding/tree/master/IBSegueAction
Difficulty: Beginner | Easy | Normal | Challenging
Prerequisites:
Be able to produce a “Hello, World!” SwiftUI iOS application
Terminology
Segue: defines a transition between two view controllers in your app’s storyboard file
@IBSegueAction: An attribute that can be used to create a segue’s destination view controller in code using a custom initializer with any required values
Initializer injection: A form of dependency injection where dependencies are provided to an object via its constructor during the creation of the object
Example of Segue
This is available on my repo, and in there is a folder “original”.
Simply put, a view controller is linked to two others simply through modal segues (in a storyboard).
Each of the SecondViewController
and ThirdViewController
have an integer that can be populated through property injection.
class SecondViewController: UIViewController {
var myNum: Int?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .gray
print(myNum)
}
}
This is populated through the ViewController.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "first" {…