SwiftUI Modifiers
Modifiers in SwiftUI can do more than apply styling.
Modifiers, in SwiftUI, are like styles in other systems. Modifiers simply add more features to a component view. For example, changing the background color of an HStack
to blue or changing its foreground color to white. When you declare a component view you very often give it at least one modifier (I assume padding()
is a top favorite).
Custom Modifiers
You can, of course, create your own modifiers. They behave mostly like the built-in ones, and can be a handy way to avoid replicating the same set of modifiers. For instance, you might want all of your primary buttons to be capsule-shaped, have a green background, with bold white lettering, and with a subtle shadow:
Button("Push Me") { } .padding(10) .background(Capsule().foregroundColor(.green)) .foregroundColor(.white) .font(.system(size: 17, weight: .bold, design: .default)) .clipped() .shadow(radius: 6)
That’s a bunch of code to duplicate each time you want to have a primary-style button in your app, so a custom modifier is the way to go:
struct PrimaryButtonModifier: ViewModifier { func body(content: Content) -> some View { content .padding(10) .background(Capsule().foregroundColor(.green)) .foregroundColor(.white) .font(.system(size: 17, weight: .bold, design: .default)) .clipped() .shadow(radius: 6) } }
And its now easy to apply:
Button("Push Me") { } .modifier(PrimaryButtonModifier())
Packaging a bunch of styling modifiers into a single place is nice and all, but modifiers can be even more helpful. Here are two examples that I’ve recently created.
Tap to Copy
I have this app which displays a bunch of Text
components inside of a Form
. I wanted the user to be able to tap on one and have the text copied to the clipboard. Because I had more than one of these, I created a modifier to do it:
struct CopyModifier: ViewModifier { let field: String @State private var showCopyAlert = false func body(content: Content) -> some View { content .contentShape(Rectangle()) .onTapGesture { UIPasteboard.general.string = field showCopyAlert.toggle() } .alert("Field was Copied", isPresented: $showCopyAlert) { Button("OK", role: .cancel) { } } } }
This modifier has a property, field
, which is the string to copy. The body
of the modifier:
adds a
contentShape
so it has a large tappable area. I do this withHStack
components to make sure even the whitespace in it can be tapped;uses the
onTapGesture
to receive the tap and copy thefield
to the clipboard (akaUIPasteboard
). Then it triggers analert
;adds an
alert
to let the user know the field was indeed copied.
Now you can use it like this:
HStack { Text(data.field1) Spacer() }.modifier(CopyModifier(field: data.field1))
Hide Sheet
In one of my apps, I wanted to make sure any sheet
s being displayed were closed when the app became inactive. In a non-SwiftUI app I might have sub-classed the view and handled the event there, but since we cannot subclass struct
s, the next best thing was a modifier. Since I had a few sheets in the app, I created a modifier to do it:
struct HideSheetModifier: ViewModifier { @Environment(\.presentationMode) var presentationMode @Environment(\.scenePhase) var scenePhase func body(content: Content) -> some View { content .onChange(of: scenePhase) { newPhase in switch newPhase { case .inactive: presentationMode.wrappedValue.dismiss() default: break } } } }
You apply this modifier to the top level View
of your sheet
and it:
uses the
@Environment
object,scenePhase
, to detect when the app is going inactive;uses the
@Environment
object,presentationMode
to dismiss the sheet.
This modifier will only apply to any sheets active, usually one, but if you layer of sheets, this will dismiss each one that has this modifier.
Summary
SwiftUI modifiers are not just for making things look good and simplifying styling. Modifiers can be pretty powerful and really extend the function of Views. Modifiers can use @Environment
and @EnvironmentObject
objects, be passed properties, apply gestures, etc. Since they are structs
you can also make use of @State
and @StateObject
as well as having functions of their own.
I suspect my future apps will have way more modifiers than they do now. I hope yours do too.
An Introduction to Combine
Replace the Delegate pattern with Combine
Using Combine to Replace the Delegate Pattern
Preface
There are now a lot of articles and books about Combine. You’ve probably tried it yourself. Maybe you thought it was just for SwiftUI and since you haven’t migrated apps to SwiftUI, you’ve ignored it for now. Well, I decided to hop on the Combine bandwagon at the urging of a co-working, and it was quite the revelation. Making me think in a whole new way. SwiftUI makes you think differently about writing UI code, and relies on Combine, but extracting Combine and using it with a UIKit app, can really drive home its power.
So I’ve cooked up a little example to show how you can replace a very well used design pattern, the Delegate Pattern, with Combine. I will skip the Combine intro since you can find that in many places now. Just suffice it to say that you have publishers and subscribers and I’ll show how these are used in place of delegates.
Set Up
Let’s set up a simple project to illustrate how to replace the Delegate Pattern with Combine publishers and subscribers.
I’m calling the project FoodFacts
because I will expand on this in a future article and use the foodfacts.org API. But for now, the concentration will be on an example to show how delegates can be replaced with Combine.
In this example we’ll have a blank screen with a User Profile button that calls up a sheet with fields for a user’s first and last names along with a Save button. The idea is to transfer the data entered into the fields back to the calling UIViewController
.
Your first reaction to doing something like this would be to create a UserProfileViewController
and a UserProfileViewControllerDelegate
. The main UIViewController
would implement the delegate and when the Save button on the UserProfileViewController
sheet was picked, invoke the delete’s function to transfer the values back. Here’s how you would do the same thing with Combine.
The code below shows the ViewController
(the main controller) and the UserProfileViewController
. There is a storyboard that goes with this but that is not particularly germane to this example.
class ViewController: UIViewController { @IBOutlet weak var yourNameHere: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. title = "Food Facts" } } class UserProfileViewController: UIViewController { @IBOutlet weak var firstName: UITextField! @IBOutlet weak var lastName: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func saveProfile(_ sender: Any) { // to do dismiss(animated: true, completion: nil) } }
You can see in the UserProfileViewController
the action for the button as saveProfile(_:Any)
which right now, just dismisses the sheet.
Now Combine
The first thing we’re going to do to UserProfileViewController
is
import Combine
This brings in the Combine framework so you can begin using it. The idea is that when the Save button is picked, rather than calling upon a delegate and using its functions, we’re going to publish the values and the main ViewController
is going to receive them and use them.
Essentially, the class you would normally use to implement a delegate’s method is the subscriber while the user of the delegate is the publisher.
Now we need something to publish. I created a simple UserProfile
struct that contains the first and last name values and this is what will get published.
struct UserProfile { let firstName: String let lastName: String }
Switching back to UserProfileViewController
, add this line below the @IBOutlet
s:
public var userDataPublisher = PassthroughSubject<UserProfile, Never>()
This line creates a PassthroughSubject
publisher that simply passes on whatever values it is given to send. Values that are UserProfile
type and this publisher never produces any errors (ie Never
).
Down in the saveProfile
function, add these lines:
if let firstName = firstName.text, let lastName = lastName.text { let profile = UserProfile(firstName: firstName, lastName: lastName) userDataPublisher.send(profile) // done with this controller dismiss(animated: true, completion: nil) }
Once the text from the first and last name UITextField
s are extracted, a UserProfile
is created from them and then sent through the userDataPublisher
. That’s it. There is no delegate to access, you are just sending out a UserProfile
to whatever is listening for it.
To that end, switch over the ViewController
and import Combine
into this file, too. Once you’ve done that, we need to subscribe to the userDataPublisher
in UserProfileViewController
.
I set the project up to use segues right in the storyboard, so we need to intercept the segue. If you were doing this with a delegate you would probably do that is the same place.
Override a function in ViewController
called prepare(for:UIStoryboardSegue,sender:Any?)
like this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? UserProfileViewController { destination.userDataPublisher .sink(receiveValue: { (userProfile) in print("Received profile: \(userProfile)") self.yourNameHere.text = "Welcome, \(userProfile.firstName) \(userProfile.lastName)" }) } }
Once you’ve secured the destination UserProfileViewController
, you set up the subscription. That’s done using the .sink
function provided by the publisher interface. The value being received is the UserProfile
created in the saveProfile
function of UserProfileViewController
. In this example I’m printing it out as well as setting the UILabel
.
But wait, there’s a problem: the compiler is flagging the .sink
with a warning that its return value is not being used.
One important thing about Combine publishers is that they don’t work without subscribers (which you created with the .sink
). And subscribers do not exist unless you keep them someplace. The result of the .sink
is something called a Cancellable
which allows you to programmatically cancel a subscription which then means the publisher will no longer publisher.
At the top of the file, below the @IBOutlet
for the UILabel
, add this line:
private var userProfileSubscription: AnyCancellable?
This will hold the result of .sink
. Here is the completed prepare
function code:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? UserProfileViewController { userProfileSubscription = destination.userDataPublisher .sink(receiveValue: { (userProfile) in print("Received profile: \(userProfile)") self.yourNameHere.text = "Welcome, \(userProfile.firstName) \(userProfile.lastName)" }) } }
So what’s happening?
When the button in the UI is tapped to trigger the segue,
prepare
is called.The
UserProfileViewController
is assigned to thedestination
.A subscription is created to the
userDataPublisher
inUserProfileViewController
.The subscription is stored in the
userProfileSubscription
so it can be cancelled but more important, it will not disappear when theprepare
function ends.
So now you can run the app.
Tap on the User Profile button. The sheet slides up.
Fill in the first and last name fields.
Tap Save.
The first and last name are printed and appear in the
UILabel
.
Instead of using a delegate, you have used Combine. You published the data you wanted to transfer and picked that up by the ViewController
.
The benefits to this are not obvious at first, except maybe that there is a good separation of the two parts (ViewController
and UserProfileViewController
). Any part of the app that has access to the publisher can subscribe to it. If the user’s profile is something that could change at any time from anywhere, you might consider moving the publisher out of UserProfileViewController
to some place more universal and the view controller just becomes the interface to publish the changes and multiple places could pick it up. One place might change a greeting on the main navigation bar. Another place might store the profile in a database locally while another part of the app sends it off to a remote system. That just is not easily achieved using delegates.
Completion
The thing about publishers is that they keep publishing while there are subscribers and while they haven’t completed. Right now, the userDataPublisher
sends out the UserProfile
and then the UserProfileViewController
is dismissed. A better way is to send all the data and when finished, send a completion. Open UserProfileViewController
and go to the saveProfile
function and add this line right below the send
call:
userDataPublisher.send(completion: .finished)
What this does is send a notice of completion to all subscribers (aka, ViewController
) that says “this is all I’m going to send, I’m done.” Now back in ViewController
, change that .sink
expression to this:
.sink(receiveCompletion: { finalResult in print("Final Result is: \(finalResult)") }, receiveValue: { userProfile in print("Received profile: \(userProfile)") self.yourNameHere.text = "Welcome, \(userProfile.firstName) \(userProfile.lastName)" })
The .sink
now has two parts: one to handle the completion event and one to handle the received value. In the receiveValue
part, the UserProfile
is put to use while in the receiveCompletion
the finalResult
is just printed. If you run this now, fill in the first and last names and pick the Save button, not only does the UserProfile
get picked up, but the send(completion: .finished)
is picked up in the receiveCompletion
part and “finished”
is printed.
This is a little more complex, but you’ll see below how useful this can be. In the meantime, remove the dismiss
call from the saveProfile
function of UserProfileViewController
and put it inside the receiveCompletion
handler.
Since the ViewController
is responsible for presenting the User Profile sheet, it should also be responsible for taking it away. A great place to do that is in this completion handler of the .sink
.
.sink(receiveCompletion: { finalResult in print("Final Result is: \(finalResult)") self.dismiss(animated: true, completion: nil) }, receiveValue: { userProfile in print("Received profile: \(userProfile)") self.yourNameHere.text = "Welcome, \(userProfile.firstName) \(userProfile.lastName)" })
If you run the app now, it works just as it did before, but the Save button code won’t dismiss the sheet; it gets dismissed as a result of sending the completion. Think about this for a second: the sink’s receiveValue
is called each time the publisher has something to send. The receiveCompletion
is called when a finish
(or a failure
- more on that below) is sent; this also closes the publisher and prevents any more things from being sent. It gives you an opportunity for clean up: close a dialog (like here), clear memory, save data, etc.
Improvements
While things are working, this is not the best way to implement it. One problem is that any object that gets hold of the userDataPublisher
can publish UserProfile
values. You really do not want that. Instead, for this example, you want only the UserProfileViewController
to publish and ViewController
to subscribe but not have the ability to publish.
Open UserProfileViewController
again. You’re going to make a bunch of small changes which ultimately hide the actual publisher and offer a proxy instead which can only be used to listen for events.
First, rename userDataPublisher
to userDataSubject
and make it private
as in:
private let userDataSubject = PassthroughSubject<UserProfile, Never>()
Ignore the compiler warnings and errors and add a new userDataPublisher
:
public var userDataPublisher: AnyPublisher<UserProfile, Never> {
userDataSubject.eraseToAnyPublisher()
}
From ViewController
’s point of view, nothing has changed. The userDataPublisher
is still a publisher. It’s a ‘generic’ publisher that sends out UserProfile
s and never fails. The benefit here is only UserProfileViewController
can send events due to userDataSubject
being private. The generic AnyPublisher
can only publish.
One more thing: the saveProfile
has to use userDataSubject
and not userDataPublisher
so change that over, too.
When you run the app, it behaves just as it did, but now the publisher is more secure.
Errors
Up until now, the publisher sent out UserProfile
s, but not errors. But what if the stuff you are having the user enter has an error in it? For example, they forget to enter the last name.
When you use delegates, you can handle this a number of ways: allow empty strings or nils to be sent through and let the ViewController
worry about it. That’s not really good. A better way is to make use of the Error portion of Combine publishers.
Go back to UserProfile
and add in this custom Error:
enum UserProfileError: LocalizedError { case firstNameMissing case lastNameMissing var errorDescription: String? { switch self { case .firstNameMissing: return "First Name is missing" case .lastNameMissing: return "Last Name is missing" } } }
Go back into UserProfileViewController
and change both the userDataSubject
and userDataPublisher
lines by replacing the Never
error type with UserProfileError
as the error type:
private let userDataSubject = PassthroughSubject<UserProfile, UserProfileError>() public var userDataPublisher: AnyPublisher<UserProfile, UserProfileError> { userDataSubject.eraseToAnyPublisher() }
You have to tell what you are publishing: the type of data (UserProfile
) and the type of Errors (UserProfileError
). Now make these changes to the saveProfile
function:
@IBAction func saveProfile(_ sender: Any) { // create a UserProfile from the text fields and publish it if let firstName = firstName.text, let lastName = lastName.text { if firstName.isEmpty { userDataSubject.send(completion: .failure(.firstNameMissing)) } else if lastName.isEmpty { userDataSubject.send(completion: .failure(.lastNameMissing)) } else { let profile = UserProfile(firstName: firstName, lastName: lastName) userDataSubject.send(profile) userDataSubject.send(completion: .finished) } } }
Rather than just blindly send out whatever is entered into the first and last name fields, we’re going to check for validity and if either one is missing (blank), a failure is sent rather than a UserProfile
or the .finished
completion.
Think about this for a minute: when the data is good, you
send
it. But if there’s a problem, youfail
it. And you can fail it with a customError
that can be as simple as static cases or it can include more data and information; whatever you need to convey the problem.
This gets handled in the .sink
’s receiveCompletion
handler back in ViewController
:
if case .failure(let error) = finalResult { let alert = UIAlertController(title: "Missing Data", message: error.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) }
I think if case
is a new construct for Swift so its syntax is a little strange, but it lets you test enum values which are not Equatable
without a full switch
statement. If the finalResult
is a failure
, this will post an alert with the message from the error. If you run the app again and leave out one of the fields from the sheet, you’ll see the Alert pop up.
Summary
What I’ve done is abolish the Delegate Pattern, at least for simple things. If you have controllers with complex delegates, Combine might not be the best thing, but keep in mind that Combine can do some powerful stuff (like filter
and map
) or perhaps you will need several publishers. Making your app more reactive should also make it less vulnerable to problems and more easily scalable.
This is the complete ViewController.swift
file. You can see that in the .sink
completion, the dismiss
function’s completion handler is used to examine the failure. This makes sure the sheet has been removed before posting the Alert; iOS gets touchy about having multiple view controllers showing up at the same time.
import UIKit import Combine class ViewController: UIViewController { @IBOutlet weak var yourNameHere: UILabel! // must retain the subscription otherwise when `prepare` function exits the // subscription will cancel. private var userProfileSubscription: AnyCancellable? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. title = "Food Facts" } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? UserProfileViewController { // when the segue is about to begin, set up the subscription to the publisher // to get the user profile data userProfileSubscription = destination.userDataPublisher .sink(receiveCompletion: { finalResult in self.dismiss(animated: true) { // using a custom Error you can give very specific feeback to the user if case .failure(let error) = finalResult { let alert = UIAlertController(title: "Missing Data", message: error.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } } // get rid of this dependency self.userProfileSubscription = nil }, receiveValue: { userProfile in self.yourNameHere.text = "Welcome, \(userProfile.firstName) \(userProfile.lastName)" }) } } }
This is the complete UserProfileViewController.swift
file.
import UIKit import Combine class UserProfileViewController: UIViewController { @IBOutlet weak var firstName: UITextField! @IBOutlet weak var lastName: UITextField! // keep the publishing subject private so nothing else can publish data to it. private let userDataSubject = PassthroughSubject<UserProfile, UserProfileError>() // make this generic publisher availble instead and it can only be used to // listen for changes public var userDataPublisher: AnyPublisher<UserProfile, UserProfileError> { userDataSubject.eraseToAnyPublisher() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func saveProfile(_ sender: Any) { // create a UserProfile from the text fields and publish it if let firstName = firstName.text, let lastName = lastName.text { if firstName.isEmpty { userDataSubject.send(completion: .failure(.firstNameMissing)) } else if lastName.isEmpty { userDataSubject.send(completion: .failure(.lastNameMissing)) } else { let profile = UserProfile(firstName: firstName, lastName: lastName) userDataSubject.send(profile) userDataSubject.send(completion: .finished) } } } }
This is the complete UserProfile.swift
file containing both the UserProfileError
and the UserProfile
itself.
struct UserProfile { let firstName: String let lastName: String } enum UserProfileError: LocalizedError { case firstNameMissing case lastNameMissing var errorDescription: String? { switch self { case .firstNameMissing: return "First Name is missing" case .lastNameMissing: return "Last Name is missing" } } }
Using Targets to structure your IOS app
Using targets to separate your concerns.
Just thought I’d pass this concept along. If your app is big (code-wise) or is going to be big or you think it may become big, here is a technique to help you manage all of the parts in a nice, testable, compact way.
When you first start out writing iOS apps, you may have a vague notion about “targets” which is, simply, the thing that gets built. In other words, your app; the target of the build process is your app. You may have asked yourself, why would I want to use multiple targets in a project? One reason may be you have a Watch app to complement your app or you may have a Widget. Here, though, I will show you how you can use targets to organize your code to make your app more manageable.
I don’t have a GitHub repository this time, because the code itself is almost irrelevant. Its the concept here that’s important.
So imagine you have a travel app. The app has four distinct parts: booking a flight, reserving a hotel room, renting a car, and managing your travel account. For the sake of making my point, further imagine each of these parts has its own tab in the app. It is not important to this technique that your app use tabs but it is important that you divide your app into separate functional bits. Using tabs as an example makes it easier to conceptualize.
When you think about this app, it’s pretty clear that there are four distinct UI pieces. But there are a lot of things each piece shares. For example, string, graphic and color assets. Your app might also need to present a login screen at any time on any tab. Your app might have extensions to classes like Date, String, or View that are used on all of the screens involved with each tab.
Your app could be divided as follows (not comprehensive, just a sample):
Common Code
Assets (string, color, graphic)
Services (connection to remote systems)
Class extensions (Date, String, etc.)
Data models
Shared views (calendar picker, price calculator, chat with travel agent, login)
The App Itself
AppDelegate
ContentView
Booking tab
Booking View
Flight schedules
Flight selector
Hotel tab
Hotel View
Reservation systems
Car rental tab
Car Rental View
Car rental company selector
Rates and discounts view
Account tab
Profile View
Preferences and personal settings
Payment information
One more thing for your imagination: can you see developing each of things things almost independently? For example, booking flights by designing the screens to do that, updating the common data models, sending and receiving data between the app and the backend booking systems. That set of views that make up the booking tab is almost in and of itself, an app.
And this is where Xcode targets come in. Each of those bullet points above could be an Xcode target. Doing that separates the parts and allows each part to be independently built and tested. Each time you create something you can ask, “Is this going to be used exclusively here or could it be used in another part of the app?” If the answer is the latter, then you put that into the Common target.
Doing this is easier than you might think. If you already have an Xcode project set up to build an iOS app, follow these steps to add another target:
Select File-> New -> Target from the File menu.
In the dialog that appears, scroll down to the Application section and pick “App”. If you are a seasoned Xcode you, you could actually use something else, but picking an actual App as a new target allows you to run your code on its own. For example, as you build the Account target, your app can log into the backend system, create a user, update it, etc. You do not need to launch the whole (Main) app to test these pieces.
On the next screen, fill in the name (eg BookingModule or BookingTab) and pick Finish.
Your target is now part of your Xcode project. If you look at the schemes menu, you will see each appearing which means each can be built, tested, and run separately.
Go head back to the Common target which you can add in exactly the same way. The purpose of this target is to be a single place for all of the code that’s shared between the other targets. To use any of the code in this target (Common) with another target (say, Booking), you need to make sure it is included in the build for that target.
Pick a file in the Common target and open the File Inspector (options+command+1). There’s a section in the panel called “Target Membership”. The Common target will already be selected. Check the box next to all of the other targets that will use this common file.
You may have heard or read that building your own SDK is a good idea (such as the code that would be in the Common target of this example). And it is - it certainly makes building your app faster as the code in the SDK is built once, on its own, and just linked into the app. That would be the next level beyond this technique and if you want to do that, go for it!
Once all of the files are selected to be included in the right targets you can assemble the app in the App target. This will be the original target that is the app itself. It will be just like building an app normally, except most of the files will reside in other targets.
The advantages to this technique are:
Forces you to think about your app as an assembly of parts.
Each part of the app is nearly independent and can be run and tested, to some degree, without the other parts. Don’t under estimate the value here. While you develop the hotel reservation target, your QA team could be testing the flight booking target.
Organizing common code into its own target makes it easier to update as the changes apply across the app.
Faster on-boarding of new team members and its easier to divide up the work.
How you divide your app up is, of course, up to you. But if this gets you thinking about code organization - even if you just use folders instead of targets - then it will be worth it. New members to the team will have a much easier time figuring out where things are and how the app works.
Happy Coding
Modal Dialogs with SwiftUI
A centralized way to display modal dialogs from anywhere inside a SwiftUI app.
A modal dialog is an interaction that interrupts the normal workflow and prevents anything happening except the dialog. The old Alert is a perfect example. When an Alert comes up you can do nothing but engage with the Alert.
SwiftUI has the Alert, but if you want to roll your own modal dialogs you have a take some things into account. You can use a SwiftUI Alert anywhere in your app. When the Alert is activated, it rises about all other content and puts up an input block to the rest of your app. Once the Alert has been addressed, it and the block go away.
And this is a key point: it rises above all other content no matter where in your View hierarchy it has been dispatched. If you want this same behavior in a custom modal dialog, you have to place it at the top of your View hierarchy, generally on the ContentView
or whatever you are using as your main View.
I’ve come up with a way that makes it easier to mange and allows you to invoke your dialog anywhere in your app. The solution lies with two things: ObservableObject
(in the form of a model) and enum
s with associated values.
A little while ago I wrote two blog articles: MultiDatePicker
and custom sheets using .overlay
. I’m going to combine these two in this article to show you what I came up with.
The Problem
First, it is not important that you use MultiDataPicker
. I am using it here because its a control that takes a binding element and could work well as a modal dialog. But I could also use a TextField
just as well. The custom sheets article basically moves the presentation of the sheet into a ViewModifier
. I will use some of that here.
Secondly, I am creating a single modal dialog, but if you want to have different types (eg, pick a date, enter a phone number, rate a restaurant, etc.), you can easily adapt this example.
The idea is that from anywhere in your app you want to present the user with a modal dialog. The dialog should be above everything else and it should provide an input blocker so the user cannot use the app without addressing the modal dialog. Now I’m not saying using modal dialogs is a good or bad idea. But sometimes you need to get some info from the user at a particular point in time. For example:
You are on a travel site and pick the tab at the bottom for hotels.
The tab shows you a view with a list of hotels. You tap one of the hotels and navigates to a detail view about that hotel.
You pick the “Reservations” button, taking you a step deeper into the app to the reservations view.
Now you are on the Reservations view with a place to set your dates. You have traveled to:
ContentView
->Hotel List View
->Hotel Detail View
->Reservations View
.You now tap the dates field. If the app uses the SwiftUI
DatePicker
you are golden because it already operates as a modal dialog. But the developer of this app wants you to pick a date range (eg, check in, check out) decided to useMultiDatePicker
instead.The
MultiDatePicker
appears floating above all other contents - the Navigation bar and the Tab bar, too, not just the content of the Reservations Screen (which might actually be a sub-area of another screen).
The Solution
The Dialog Model
We begin with the Dialog Model. This is a class
that implements ObservableObject
because we want to use it to set the type of dialog to open.
class DialogModel: NSObject, ObservableObject { @Published var dialogType: DialogType = .none }
You see that it has a single @Published
value for the dialogType
. That is an enum
defined as follows:
public enum DialogType { case none case dateDialog(Binding<ClosedRange<Date>?>) // add more enum cases and associated values for each dialog type. }
What’s interesting about this enum
is that for the dateDialog
member, there is an associated value of ClosedRange<Date>?
wrapped as a Binding
. And it just so happens the MultiDatePicker
has an initializer that also calls for an optional closed date range.
The Dialog Modifier
The next thing we are going to do is create a ViewModifier
to activate the modal dialog based on the dialogType
value of the DialogModel
.
private struct DialogModifier: ViewModifier { // 1. @ObservedObject var dialogModel: DialogModel func body(content: Content) -> some View { content // 2. .overlay( Group { switch dialogModel.dialogType { // 3. case .dateDialog(let dateRange): ZStack { // 4. Color.black.opacity(0.35) .zIndex(0) .onTapGesture { withAnimation { self.dialogModel.dialogType = .none } } // 5. MultiDatePicker(dateRange: dateRange) .zIndex(1) } .edgesIgnoringSafeArea(.all) default: EmptyView() } } ) } }
Some important bits about this DialogModifier
:
This
ViewModifier
needs to use theDialogModel
instance, so it is declared as an@ObservedObject
because it implements theObservableObject
protocol and because we want this to react to changes in its@Published
member,dialogType
.An overlay is used to place Views above the
content
. AGroup
is used to select what to put into the overlay: anEmptyView
if no dialog is being displayed or aZStack
with the overlay Views.A
switch
andcase
statement select for the dialog and grabs theBinding
from the enum’s associated value.A simple
Color
is used for the blocker and a tap gesture set to make it possible to dismiss the dialog.The
MultiDatePicker
itself, passing theenum
’s associated value (dateRange
) at initialization.
One thing to note: use static .zIndex
values if using transitions with Views (which I did not use here, but you might want them).
Now let’s make this clean to use in the application with a little View
extension:
extension View { func dialog(_ model: DialogModel) -> some View { self.modifier(DialogModifier(dialogModel: model)) } }
Applying the Dialog Modifier
This little extension function makes it a little bit nicer to apply the modifier:
import SwiftUI @main struct PlanWizardApp: App { // 1. @StateObject var dialogModel = DialogModel() var body: some Scene { WindowGroup { ContentView() // 2. .environmentObject(dialogModel) // 3. .dialog(dialogModel) } } }
Declare and instantiate the
DialogModel
. You want this to stick around so use@StateObject
.Pass the
DialogModel
down into the app content views.Apply the
DialogModifier
through the handy extension function, passing along theDialogModel
.
That has set everything up. I told you that the dialogs needed to be at the top level, so it is in the App
definition! When the DialogModel
’s dialogType
enum
is set, the DialogModifier
will take notice and display the appropriate dialog as an overlay on ContentView
.
Showing the Dialog
So how do you actually make this work? Let’s assume you’ve got a Form
someplace and it is from there you want to pop up the MultiDatePicker
and display a date:
// 1. @EnvironmentObject var dialogModel: DialogModel // 2. @State private var dateRange: ClosedRange<Date>? = nil Form { // ... Section(header: Text("Dates")) { HStack { Text("\(dateRange)") // 3. Spacer() Button("Pick Dates") { // 4. self.dialogModel.dialogType = .dateDialog(self.$dateRange) } } } }
Bring in the
DialogModel
for use in this View (see step 4).Declare a
var
to hold the selected date range. In a real app you probably have this as part of some data model.Display the range selected. You will need a little more code here, but the idea is to show that this value has in fact changed.
Here is the key. When the
Pick Dates
button is tapped, theDialogModel
is set with the.dateDialog
value and the associated value for theenum
is set as a binding toself.dateRange
. This is passed into theMultiDatePicker
by theDateModifier
. And because thedialogType
is an@Published
var
of theDialogModel
, SwiftUI will cause theDateModifier
to be executed and theMultiDatePicker
will appear as an overlay ofContentView
inside aZStack
.
Summary
Maybe the ending was a little anticlimactic, but I think it paid off nicely.
Overlays only apply to the View they are attached to. If you want a “dialog” to appear above all other content you have to place the overlay on the topmost View. In this case,
ContentView
. And do so in theApp
definition.Overlays are modifiers, so a good place to encapsulate them is with a custom modifier like
DialogModifier
. It can check a flag to see if the dialog view should be displayed or not. In this case itsdialogType
of theDialogModel
.You need to communicate the desire to see the dialog from anywhere in the app code all the way up to the
app
definition. The best way to do that in SwiftUI is with anObservableObject
shared throughout the app using@EnvironmentObject
(you could also define this as an@Environment
if you prefer).You also need to communicate data from the dialog back to whatever wants to see it (generally to a
@State
var declared in the View that triggered the dialog’s appearance). One way to do that is through anenum
with an associated value that is aBinding
.Combining the
enum
setter with@Published
in theObservableObject
model make a good way to trigger the appearance of the dialog as well as provide a data bridge using aBinding
.
So there you have it. I hope if you need dialogs (or even a centralized location for .sheet
and .alert
modifiers) you will find this solution handy.
Sheets with SwiftUI
An alternative to full screen action sheets using overlays in SwiftUI
If you’ve been using SwiftUI for a while now, you have undoubtedly come across the .sheet
modifier. This takes a View and turns it into a slide-up view. Sheets are a great way to quickly display ancillary information or get some quick input from the user.
The problem with .sheet
is that on the iPhone, it is a full screen affair. If you want to bring up a few details, a full screen sheet may not be what you want; the .sheet
on the iPad is different; it floats up to the middle of the screen and does not take over the entire display.
What I’ve come up with is a different take on the sheet, using the .overlay
modifier. In this article I will show you my HalfSheet
and QuarterSheet
overlays.
The code for this article is available in my GitHub Repository.
Normally, an article like this takes you on a journey, from the inception to building up the code to the final version. I’ve decided to just jump right into it and explain how it works. I’ll begin with how to use my half- and quarter-size sheets. Bear in mind that these are overlays and come with the caveats around overlays. Which are:
Overlays are the width of the view they are overlaying. You can modify that using
.frame
with the size of the screen. I have not done that in this exercise.Overlays only overlay the view they are attached to. If you are expecting the overlay to always be on top, you should use
.overlay
at the highest level (eg,ContentView
).
How to Use The Sheets
The syntax for these sheet overlays is:
.halfSheet(isPresented: Binding<Bool>, content: ()->Content) .quarterSheet(isPresented: Binding<Bool>, content: ()->Content)
You pass a binding to the sheet overlay and supply the content you want to see inside the sheet overlay. For example:
AnyView() .halfSheet(isPresented: self.$showHalfSheet) { SheetContents(title: "1/2 with Modifier") } .quarterSheet(isPresented: self.$showQuarterSheet) { SheetContents(title: "1/4 with Modifier") }
The SheetContents()
view is irrelevant and you can see it in the screen shots. It’s just the content of the sheet.
To show the sheet, the app should change the binding within a withAnimation
block. For example:
Button("Show 1/2 Sheet") { withAnimation { self.showHalfSheet.toggle() } }.padding()
The withAnimation
is necessary to trigger the transitions that are set up on the sheet overlays, which is shown later in this article.
So what are halfSheet
and quarterSheet
exactly? Let’s leave that for a moment and look at the overlay content itself.
The Code
PartialSheet
If you look at the code, you will find PartialSheet
. This is actually the overlay content being shown as the sheet. It is what wraps SheetContents
that you don’t see. Both the quarter and half sheet overlays use this.
struct PartialSheet<Content: View>: View { @Binding var isPresented: Bool var content: Content let height: CGFloat @State private var showingContent = false init(isPresented: Binding<Bool>, heightFactor: CGFloat, @ViewBuilder content: () -> Content) { _isPresented = isPresented height = heightFactor self.content = content() } var body: some View { GeometryReader { reader in ZStack(alignment: .bottom) { BlockingView(isPresented: self.$isPresented, showingContent: self.$showingContent) .zIndex(0) // important to fix the zIndex so that transitions work correctly if showingContent { self.content .zIndex(1) // important to fix the zIndex so that transitins work correctly .frame(width: reader.size.width, height: reader.size.height * self.height) .clipped() .shadow(radius: 10) .transition(.asymmetric(insertion: .move(edge: .bottom), removal: .move(edge: .bottom))) } } } .edgesIgnoringSafeArea(.all) } }
PartialSheet
has three properties: the isPresented
binding, the content
to show inside (eg, SheetContents
from above), and the height
which is the percentage of the height to use.
The content comes in the form of a @ViewBuilder
which is what lets this accept any View to use as the sheet (content
inside).
I’ve used a GeometryReader
to be able to get the dimensions of the area for the overlay which is used in the .frame
and sets the height from the height
value passed in.
I’ve used a ZStack
to layer the components. There is BlockingView
which is just a Color
with a .onTapGesture
to let the user tap in this area to dismiss the overlay; it is the translucent area between the sheet and the main app contents (see the screen shots).
When using transitions with
ZStack
it is important to use fixed.zIndex
values. This tells SwiftUI that these views should be reused and not re-created. If you leave off the.zIndex
, SwiftUI will create new instances when the transitions happen and the transitions will not work as you expect.
Above the BlockingView
is the actual content
with a bunch of modifiers. One of the modifiers is the .frame
to give it its height and a .transition
to handle is appearance and disappearance. The .move
will bring the view onto and off of the screen from the bottom. There is also a .shadow
(and use .clipped
so the shadow does not leak into the content).
The .edgesIgnoringSafeArea
is applied to the outer component (GeometryReader
) so you get a nice effect on the edges of the screen.
BlockingView
The BlockingView
provides a means to shield the main app content from gestures while the overlay sheet is visible. You do not have to use this, but I think its a nice feature and consistent with the presentation of pop-ups and other overlays; it can be detrimental to your app if you allow the user to engage with the content while an overlay is visible.
private struct BlockingView: View { @Binding var isPresented: Bool @Binding var showingContent: Bool // showContent is called when the Color appears and then delays the // appearance of the sheet itself so the two don't appear simultaneously. func showContent() { DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { withAnimation { self.showingContent = true } } } // hides the sheet first, then after a short delay, makes the blocking // view disappear. func hideContent() { withAnimation { self.showingContent = false } DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { withAnimation { self.isPresented = false } } } var body: some View { Color.black.opacity(0.35) .onTapGesture { self.hideContent() } .onAppear { self.showContent() } } }
The BlockingView
is pretty simple: it shows a Color
(I picked black
but white
gives a frosted feel). When the Color
appears it triggers the showContent()
function. An .onTapGesture
captures a tap by the user and calls the hideContent()
function.
The idea here is that you want to dim the view - THEN - show the sheet. When the sheet disappears, you want the sheet to go away BEFORE the Color
fades out. The showContent()
and hideContent()
functions use asyncAfter
to introduce a short delay while these effects run. And, importantly, they both use withAnimation
blocks to change the state. This allows that transition on the content in PartialSheet
view run correctly.
Test Run
You now have enough parts to make use of them, like this:
@State var showSheet = false var body: some View { VStack { // just for something to look at Text("Hello World") Button("Show Sheet") { withAnimation { self.showSheeet.toggle() } } } .overlay( Group { if self.showSheet { PartialSheet(isPresented: self.$showSheet, heightFactor: 0.5) { SheetContents(title: "Trial Run") } } else { EmptyView() } } ) }
The .overlay
uses a Group
so that it shows either the PartialSheet
or an EmptyView
. The button changes the Bool
and the sheet is displayed, SwiftUI running the transition to show it.
Let’s all well and good, but kind of messy. Your app code certainly needs to own and manage the boolean that is used to present the overlay sheet (eg, showSheet
). But the .overlay
and its content is just asking a lot, I think, if you need to use this in several places in your app.
And this is where .halfSheet
and .quarterSheet
come in. These are custom extension functions on View
which makes use of ViewModifier
.
View Extension
If you open the View+Modifiers.swift
file, you will see how halfSheet
and quarterSheet
are defined:
extension View { func halfSheet<Content: View>(isPresented: Binding<Bool>, @ViewBuilder content: () -> Content) -> some View { self.modifier(PartialSheetModifier(isPresented: isPresented, heightFactor: 0.5 sheet: AnyView(content()))) } func quarterSheet<Content: View>(isPresented: Binding<Bool>, @ViewBuilder content: () -> Content) -> some View { self.modifier(PartialSheetModifier(isPresented: isPresented, heightFactor: 0.25 sheet: AnyView(content()))) } }
The halfSheet
function, for example, applies the PartialSheetModifier
(defined below) and passes down the isPresented
binding, a heightFactor
of 0.5
(to make it a half sheet) and the content view. Using this, as shown at the beginning of this article, makes it easier for the developer to toss in a half or quarter sheet in the same vein as the SwiftUI .sheet
modifier.
Notice that
@ViewBuilder
continues to follow through the code. However, when it reaches this point, we want to actually execute the builder and create the View, which is what happens in the call to the sheet initializers -content()
. As you’ll read in a moment, the customViewModifier
is expecting anAnyView
not a builder.
The final piece of this is PartialSheetModifier
:
private struct PartialSheetModifier: ViewModifier { @Binding var isPresented: Bool let heightFactor: CGFloat let sheet: AnyView func body(content: Content) -> some View { content .blur(radius: isPresented ? 4.0 : 0.0) .overlay( Group { if isPresented { PartialSheet(isPresented: self.$isPresented, heightFactor: heightFactor) { sheet } } else { EmptyView() } } ) } }
PartialSheetModifier
is a ViewModifier
which is given the content (the View being modified, like a VStack
) so you can add your own modifiers. Here, the content
is given a blur
effect if the sheet is being presented, and here you see the actual .overlay
finally. As you read above in the trial run, the .overlay
is a Group
with a test that presents the sheet or an EmptyView
.
To sum this up
An
.overlay
is used to show the “sheet” which is whatever content you want in that sheet.@ViewBuilder
is used to make it as flexible as possible to show content.The
.overlay
is placed into a customViewModifier
which itself is placed inside of a View extension function (eg,halfSheet
).The
halfSheet
andquarterSheet
View extension functions usePartialSheet
just to pass in a specific height value (0.5 or 0.25).The
PartialSheet
is aZStack
with aColor
to block the user from interacting with the main app and the actual sheet content.Tap gestures to activate or dismiss the overlay sheet are done within
withAnimation
blocks so a transition can be used to hide and show thePartialSheet
.
I hope you’ve found this useful and can use it or even parts and concepts in your own apps.
A Multi-Date Picker for SwiftUI
A date picker that allows you to select more than a single day.
The information presented here is now obsolete with the introduction of iOS 16 and SwiftUI 4.0.
Many applications have the need to pick a date. But what if you have an app that requires more than one date to be selected by the user? Perhaps you are writing a hotel reservation system or an employee scheduler and need the user to select starting and ending dates or just all the days they will be working this month.
MultiDatePicker
To help facilitate that task, I’ve written the MultiDatePicker
, a handy component that can deliver a single date, a collection of dates, or a date range, to your application. You can see screen shots below.
The MultiDatePicker
is pretty easy to use. You first need to decide which selection mode you need: a single day, a collection of days, or a range. You create a @State
var to hold the value and pass that to one of the MultiDatePicker
’s constructors. When the user makes their selection your binding will be updated.
Source for
MultiDatePicker
can be found in my GitHub Library
Here are some examples:
Single Date
@State var selectedDate = Date()
MultiDatePicker(singleDay: self.$selectedDate)
In singleDay
selection mode, the MultiDatePicker
acts similarly to the SwiftUI DatePicker
component. Unlike the SwiftUI component, MultiDatePicker
can only select dates, not times.
The calendar in the control shows the month/year of the singleDay
given.
Collection of Dates
@State var anyDays = [Date]()
MultiDatePicker(anyDays: self.$anyDays)
With the anyDays
selection mode, the binding contains the user’s selected day sorted in ascending order. If the selection order matters, you should write a custom binding to intercept the changes or use the onChanged
modifier.
Tapping a day will select it and add it to the collection; tapping the day again will de-select it and remove it from the collection.
The calendar in the control will show the month/year of the first date in the anyDays
array. If the array is empty the calendar will show the current month and year.
Date Range
@State var dateRange: ClosedRange<Date>? = nil
MultiDatePicker(dateRange: self.$dateRange)
With the dateRange
selection mode, the binding is not changed until the user selects two dates (the order does not matter, the MultiDatePicker
will sort them). For example, if the user picks two dates, the binding will have that range. If the user then taps a third date, the binding reverts to nil
until the user taps a fourth date.
The calendar in the control shows the month/year of the first date in the range given. If the dateRange
is nil
the control shows the current month and year.
The Model
Making all of this work is the model: the MDPModel
. As with most SwiftUI components, the views are data driven with a model containing the data. Often you’ll have a service (a connection to a remove system or to something outside the app) that deposits information into a model which then causes the view to react to the change in the data and refresh itself with the changes.
In the case of the MultiDatePicker
, there is no service, instead the model creates the data. And the data for the model are the days of the month in the calendar displayed. My example of MultiDatePicker
shows how preparing the data up front can make writing the UI easier.
The model works from the control date - any Date
will do, as only its month and year are important. Once the control date is set, the model constructs a calendar - an array of MDPDayOfMonth
instances that represent each day. Days that are not displayed are giving a day
number of zero (these are days before the beginning of the month and after the last day of the month). As the MDPDayOfMonth
items are created, the model determines if each is selectable (see below), if one represents “today”, and what its actual Date
is so that comparisons at runtime can be efficient.
Once the days have been created they are set into a @Published
var which triggers the UI to refresh itself, displaying the calendar. The UI can then quickly examine each MDPDayOfMonth
to see how it should appear (eg, draw a circle around “today” or highlight a selected day).
More Options
In addition to the selection mode, MultiDatePicker
has other parameters, all of which have defaults.
Selectable Days
If you look at the Any Dates screen shot you can see that the weekend days are gray. These days are not selectable. The MultiDatePicker
can be told which days are eligible for selection by using the includeDays
parameter with a value of allDays
(the default), weekendsOnly
, or weekdaysOnly
(shown in the screen shot).
Excluding Days
Other options you can use with MultiDatePicker
are minDate
and maxDate
(both default to nil
). If used, any dates before minDate
or after maxDate
are not eligible for selection and shown in gray.
Jumping Ahead (or Back)
The increment (>
) and decrement (<
) controls move the calendar forward or backward one month. If the user wants to skip to a specific month and year, they can tap on the month and year (which is a button) to bring up the month/year picker, as shown in the last screen shot.
The month/year picker replaces the calendar with two wheels to select a month and a year. Once the user has done that, they tap the month/year button again and the calendar returns, showing the newly selected month/year combination.
Weather Demo for SwiftUI
A SwiftUI app to help get you started writing your iOS apps.
When you are starting out learning a programming language or system, you often go through tutorials which give you a sense of what everything is about. But then you try to code something yourself and things get fuzzy. You read about concepts and techniques and try to put them together for your own work. Its really a learn-as-go process.
I thought I’d help out a little and I created a small, but complete, SwiftUI app. The link to the GitHub repo is below. Its called “WeatherDemo” and, as the name suggests, is a weather app. I picked weather because there are a lot of weather apps so another one wouldn’t make any difference. More important though, the point of the app is straightforward but can cover a lot of topics. Being a small app its also easy to get your head around and understand the flow of the data and the lifecycle of the elements.
Here are the topics covered by WeatherDemo, in no particular order:
How to ask permission to get the device’s current location.
How to use Core Location to search for places.
How to use Core Data.
How to use URLSession with Combine to make REST API requests from openweathermap.org
How to use the Decodable protocol to digest JSON data from the remote request.
How to create custom SwiftUI components.
How to use the Size Trait Classes to handle different screen orientations.
How to create Extensions to classes.
How to do simple localization to support multiple languages.
How to use SVG images in SwiftUI apps.
The app requires iOS 14 and Xcode 12. You will also need an account with openweathermap.org (the free account is enough) in order to run the app.
You can download or clone the GitHub repository here at weatherdemo-ios.
There is an extensive README in that repository; this article is merely an introduction.
The WeatherDemo app’s structure goes like this:
Services are used to get the device location and to fetch weather information from openweathermap.org.
A controller (or model) coordinates between the services, fetching new weather information as needed. The controller is an
ObservableObject
and@Published
a set of values which are observed by the UI components. These areCombine
framework items.The
ForecastView
displays the weather data in the controller. Because of the way SwiftUI and Combine work, telling the controller to get weather info for a new location will cause theForecastView
to update.The
LocationSearchView
is asheet
that displays search history as well as search results while you type. Pick a search result and the controller fetches the weather for that location.
That’s really all there is to the app. You’ll find a folders for helper components for both the ForecastView
and the LocationSearchView
. These are custom SwiftUI components that do things like display the wind speed or a colored temperature bar or the search term field.
SwiftUI really encourages breaking your app down into small parts and composing your app out of the them. You will find that a lot but not 100% throughout the app - it gives you a chance in some places to try it out yourself.
One of the things the WeatherDemo app does is display a graphic that represents the weather (like the sun or moon in clear conditions). These images were hand drawn by me (I’m not bragging, as you’ll see, just pointing out there are no copyright issues with the images) using an SVG editor. Using SVG images in iOS app is very recent. Normally you create a graphic at three resolutions so iOS can choose the best one for the devices. As there are more and more iOS devices with different resolutions, it is much better to use scalable vector graphics. Not only do they look good across all devices, but it means there is only one image to maintain. Plus, most graphic artists can make SVG or export SVG fairly easily.
I hope you get something out of this project. I would not take WeatherDemo and hold it up as an exemplar of best practices or a template for all your endeavors. It is meant to be a bit of a hodgepodge to demonstrate techniques with a reasonable amount of coherence. With that in mind, enjoy!
SwiftUI and the Responder Chain
A nifty way to let your users travel from field to field.
While I love working with SwiftUI, there is a piece missing which I hoped Apple would address with SwiftUI 2 - the responder chain. Or more specifically, responders with respect to keyboard input. If you are unfamiliar with the concept of a responder, it’s simply how apps receive and handle events. In other words, how app components respond to events they receive. Tapping on a key in the virtual keyboard (for iOS) or a physical keyboard (for macOS) generates an event. That event must find its way to an object that will handle - or respond - to it.
The SwiftUI TextField
is woefully bereft of the ability to be assigned responder responsibility. It’s not that TextField
cannot accept input from the keyboard. It can and works just great. But what if you have a set of TextField
s such as login and password field. Normally you would tap on the login field (which causes it to become a responder and the keyboard appears), type in the user name, then press the “return” key - which is most often labeled “next” in this circumstance - and the caret jumps to the next field.
That is still not possible with SwiftUI. If you place two TextField
s on a screen, enter text into one, press “return”, nothing happens. With TextField
you can receive information once the “return” key is pressed and you can programmatically dismiss the keyboard. But you cannot get the current TextField
to resign being the responder and get the next field to become the responder. Just isn’t going to happen.
The solution is still to write a custom component using UIViewRepresentable
. That’s not too hard and I’ll show you one way in a moment. What I do not understand is why Apple has not addressed this. I can understand not providing some automatic input field chaser, but to not provide the tools to do it yourself does not seem good form. You could argue that using UIViewRepresentable
is their solution, but given what Apple have done with SwiftUI 2, seems a shame.
GitHub
I have a public GitHub repo with some code you can use and build upon. Its nothing fancy and you can muck with it as you like. It basically works like this:
It is a
UIViewRepresentable
that makes aUITextField
.It has a
Coordinator
that implementsUITextFieldDelegate
.The
Coordinator
is handling thetextFieldShouldReturn
message. It scans the surroundingUIView
hierarchy looking for the next field as specified by the current component. If it finds one, that becomes the new responder.If there is no next field, the current component resigns as the responder, effectively removing the keyboard.
To make this work, the component (cleverly called TextFieldResponder
) assigns each underlying UITextField
a unique tag, incrementing the tag numbers. The default tag is 100 for the first one, 101 for the second, and so forth. When the textFieldShouldReturn
function is called, it checks the given textField
for its tag, increments it, then finds a UIView
with that tag and makes it the responder.
You use it like this:TextFieldResponder(title: “Login”, text: self.$login)
TextFieldResponder(title: “Password”, text: self.$password)
.isSecure(true)
As with SwiftUI TextField
, the title
becomes the placeholder and the text
is a binding that gets changed as the user types. There is also a trailing closure you can implement which is called when the “return” key is tapped.
You can find my GitHub repository at: peterent/TextFieldResponder
Modifiers
You can see in the above example, the Password field is being made secure by the presence of the .isSecure(true)
modifier. This is not actually a real modifier as UIViewRepresentable
does not support SwiftUI modifiers. This is really an extension function that returns self
. There are few more I added:
keyboardType
to change which keyboard to use for the field;returnKeyType
to change the appearance of the “return” key;autocapitalization
to change how capitalization works;autocorrection
to turn auto correct on or off.
Just use them as you would any modifier.
TextFieldResponder(title: "Login", text: self.$login)
.keyboardType(.emailAddress)
.autocorrection(.yes)
.autocapitalization(.none)
Final Thoughts
This is not a perfect solution, but if you have a bunch of input fields in your app and you would like the user to quickly move between them without having to leave the keyboard and go tap on this, this is a way to do it.
SwiftUI 2.0 - First Days
A short tour of SwiftUI 2.0
I’ve spent the last couple of weeks or so looking into SwiftUI 2.0 and wanted to document my thoughts about it while it was relatively fresh. Its often good to go back and look at early impressions of things to see how your thoughts or opinions changed.
I’m pretty happy with SwiftUI 2.0 - Apple added some new “native” components and fixed some things that I had developed work-arounds for; now those are obsolete. I looked through a list of the new features and created a simple App to learn about each new thing. Then I spent time upgrading my two apps (Journal and Password) to be SwiftUI 2.0 compliant; as of this writing I have not yet released them to the Apple App Store.
Impressions
This is a brief description of some of the new components available in SwiftUI 2.0 and how I made use of them.
Maps
The idea of a native Map component was something I was looking forward to using. I created my own MapView
for SwiftUI 1.0 using UIViewRepresentable
. With SwiftUI 2.0 the expectation was that I could toss that aside.
Alas, not so quick. While SwiftUI 2.0 comes with a nice implementation of MKMapView
, it lacks interactivity that I need. You can place annotations (markers or pins) on the map, but they are not tappable. And there does not seem to be a way to get the user’s current location to indicate or track.
I decided to stick with my own MapView
for now. I’m sure Apple will address this somehow. This was the only component I was disappointed with.
Grids
One thing lacking in SwiftUI 1.0 was a way to present collections in columns or rows. What people have done is wrap UICollectionView
to do this. With the new LazyVGrid
and LazyHGrid
you do not need to do that. The “lazy” part of their names means they won’t create any children until they need to. Some folks call these virtualized lists.
Laying out a grid is easy: You create an array of GridItem
instances that describe how many columns or rows there should be and how they should be sized (basically fixed or variable). Then you just fill them. If you need to scroll them, wrap them in a ScrollView
. Each element that’s being presented should be given enough information to fill itself out. I used a LazyHGrid
to present a strip of photos that were taken near a Journal entry’s location. As each thumbnail is exposed it requests a UIImage
from the Photo library on the device, showing an activity spinner (ProgressView
for SwiftUI 2.0) until the image is available.
Scrolling
Speaking of scrolling, one pretty irritating shortcoming in SwiftUI 1.0 was the inability to scroll to a specific element within a ScrollView
. To solve that, SwiftUI 2.0 introduces ScrollViewReader
which you place inside of a ScrollView
. If you want to have a specific item brought into view, just give the ScrollViewReader
its ID
. If you place your request inside of a withAnimation
block, the ScrollView
will slide nicely right to the item.
I used this in my Journal app. When the app opens it shows a calendar. If you tap on a date, the next screen is a list of all of the entries in the month and it scrolls the view to the date you selected. In the SwiftUI 1.0 version I used a wrapped UITableView
to accomplish that. Now I can discard that part to do this exclusively in SwiftUI 2.0. This really reduced the footprint of the app and it seems to be a bit quicker, too.
Tabs
You’re probably familiar with using a tabbed application: the bottom of the screen has icons and labels for different sections of the app. Facebook for example, has your home, market place, notifications, etc. Creating these with SwiftUI 2.0 and TabView
is pretty easy.
There is however, something more that TabView
can do for you: paging. You know those screens that have tiny dots at the bottom and you swipe left and right to go between them? Well by simply using the tabViewStyle
modifier with TabView
and giving it a PageTabViewStyle
specifier, you turn your old tabs into pages. Pretty handy.
I used this with my Journal app to present a set of full-size images that might be associated with a journal entry. Once you tap on a thumbnail in the LazyHGrid
, that action displays a new screen with the full size images. You can zoom and pan on them (like Instagram) or swipe to go to another image without returning to the previous screen to select a new image.
Final Thoughts
What impresses me most is that Apple really stuck with its view composition model. For example, the LazyHGrid
does not scroll by itself. If you want that behavior, place it inside of a ScrollView
. Likewise, you can add functionality with modifiers rather than having massive components with tons of options that you won’t use most of the time. Same goes for animation. The ScrollView
will not slide to show you the item you want, you have to trigger it by placing your change inside of an animation block. This allows you to decide if you want the list to bounce into view, zip and slow down, take 2 minutes, etc.; it’s up to you.
I gave you a little taste of what is available in SwiftUI 2.0. I did not include changes to the Combine framework and Swift 5.3, but those were also welcome and I barely touched the surface of what’s capable there.
If you have been holding off going to SwiftUI, now is the best time to jump in. It is far more robust and capable than SwiftUI 1.0 - and I built a commercial app with that!
It’s so much easier and faster to build apps with SwiftUI. All of the tedium of layout constraints, actions, outlets, storyboards, XIB files, are - poof - gone.
And you do not have to go 100% into a re-write. Using the SwiftUI UIHostingController
you can wrap SwiftUI components into your UIKit code. So if you have a new screen to develop that has animation or a tricky list layout, give SwiftUI 2.0 a try.
I will try and and do another one of these in a few months as I get more experience and we can compare notes.
Simple Charts with SwiftUI
Simple, animated, charts using SwiftUI
The information in this article is now obsolete with the introduction of iOS 16 and SwiftUI 4.0
This project shows one way to use SwiftUI to make some simple charts. There is a ColumnChart
, a BarChart
, a LineChart
, and a PieChart
that animate when their data changes. The data for these charts is an array of Double
values that represent percentages. To make things a little easier there is a ChartModel
that can take any array of Double
and transform it into percentage values.
An example shows how to use the chart views, including custom data formatters to show values on the charts. Axes and grid lines can also be applied.
You can find the source code for this on my GitHub repo.
The Charts
The charts themselves are pretty simple. They are composed of SwiftUI Shape
elements and then layered in a ZStack
to give the desired effect:
GridView
(optional)The chart (
BarChart
,ColumnChart, LineChart
, orPieChart
)AxisView
(optional)
Model
The data for the chart is an array of Double
values. The values are percentages of the chart's primary dimension (height for ColumnChart
, width for BarChart
). The model, ChartModel
, converts the user data (temperatures in my example) into percentages so the chart user does not have do that conversion. The model can either use the data or it can be given a specific range (eg, -100°F to +100°F) when calculating the percentages.
The model for the PieChart
is a little different so there is a PieChartModel
, a subclass of ChartModel
. The data for the PieChart
is represented by a pie wedge which is a percentage of the total. However, to make things easier for the PieChart
, the PieChartModel
transforms the data not into a vector of percentages, but a vector of angles (in degrees).
The percentages (or angles) are then stored in a very special data type: AnimatableVector
(see below) which is @Published
in the model. When the model's data changes it triggers a new set of values and refreshes this vector.
AnimatableVector
The key to SwiftUI animation is SwiftUI's ability to interpolate between starting and ending values. For example, if you have an offset of 10 and then change it 100, if the element has an .animation
modifier, SwiftUI will smoothly move the element from the first position to the next position.
SwiftUI makes it easy to animate its own modifiers like offset, scale, and opacity (among others). But you can create your own custom animatable data. Check out Paul Hudson's post on Animating Simple Shapes.
Unfortunately, SwiftUI does not provide more than animating a single value and a pair (AnimatablePair
). What's needed for a chart is animating an array, or vector, of values.
This is where Swift's VectorArithmetic
comes in. I won't go into details here, but thanks to Majiid Jabrayilov, there is AnimatableVector
which makes chart animation possible (see Acknowledgements below). By giving a set of values to the vector, a change in that set can be animated by SwiftUI, causing the chart to fluctuate. Its a nice effect and, of course, you can play with the effects used (I just use a simple ease-in-out, but you can use others).
The App
The code in this repository is a runnable app using SwiftUI 1.0. The app itself presents both types of charts with some toggles to turn on/off some of the features.
Please feel free to use this code for your projects or to use it as another way to understand animation or just SwiftUI in general. I will probably be updating it from time to time as I learn more and improve my techniques.
Acknowledgements
Without AnimatableVector this project would not be possible. My thanks to Majiid Jabrayilov for showing me how wonderful Swift math can be. Check out his article on the magic of animatable values.
My Swift life would not be complete without Paul Hudson's Hacking with Swift blog. The man must never sleep.
Also: if you are looking for a radar (or spider) chart, check out this article from Jimmy M Andersson: Data Visualization with SwiftUI: Radar Charts.
Using Size Traits with SwiftUI
Size traits make it easy for your app to handle different screen sizes and orientations.
So Many Sizes
This article was written for SwiftUI 1.0.
Nowadays mobile devices come in a dizzying array of sizes and shapes. I’ve got an Android tablet that’s much taller than it is wide (or much wider than it is tall). Apple products also have different sizes ranging from the Apple Watch, to the iPhoneSE, to the iPhone Pro Max, to the iPad, to the Apple TV, and to the iMac and MacBook computers. With Apple’s new generation of operating systems, you will be able to write apps using SwiftUI to run on all these devices with virtually the same code base. So how do you cope with all of the different screen sizes and resolutions?
If you are an Android developer you create layout files (among other things) for the different size screens your app supports. When your app runs, the OS finds the closest layout to the size of the screen of the device and loads that. Your app’s code just refers to the “login” layout and it’s none the wiser about the size of the screen. That’s all well and good, but if your app has a tricky layout, you might have to support a lot of layout files.
Apple has taken a different approach. While you can get the actual size of the device your app is running on and use those dimensions to programmatically set your UI, that’s probably the least attractive way to go. The better alternative is to use size traits.
Size Trait Classes
Size traits basically tell you the shape of the screen using two values in both dimensions. The two values are Regular
and Compact
. If you take an iPhone and hold it in portrait orientation, the size traits for this will be vertical Regular
(or just R
) and horizontal Regular
as well. In other words, this is the device’s regular orientation. If you turn it to landscape orientation, then the traits change to vertical Compact
(or just C
) and horizontal R
. The screen’s width is still considered normal or regular
but vertically it has been compacted.
If you use an iPad, your app’s size traits are always Regular
for both dimensions unless you use split screen (to share your app with another app). Then your horizontal size trait becomes Compact
. The same will be true with Max size iPhone in landscape mode. If you app supports the main-detail split screen view, your main screen will become Compact
.
If you are using UIKit and Storyboards, Interface Builder lets you set your constraints based on different size collections. That is not covered in this post.
The point is, your layout can just react to the size trait and not worry about the actual size or even orientation of the screen.
I’ll use one of my apps as an example. Below is the app running on an iPhone SE. On the left is the app in portrait orientation and the right is landscape orientation. Not very pretty in landscape - some parts have been cut off.
To solve that, I looked at the vertical size trait and adjusted the scaleEffect
modifier of the view to shrink the UI a little so it all appears. Now compare the two screens again:
Using Size Trait Classes
So how do you actually use size traits in a SwiftUI app? It’s actually really simple.
First, in the View
you want to adjust based on size, declare @Environment
vars for the orientations you are interested in handling. Here I am just looking at vertical:
@Environment(\.verticalSizeClass) var verticalSizeClass
Now I want to scale down my interface based on the size trait, so I set the .scaleEffect
modifier accordingly:
VStack(alignment: .center) {
// content
}.scaleEffect( (self.verticalSizeClass ?? .compact) == .compact ? 0.75 : 1.0 )
Note that
verticalSizeClass
is anOptional
so you need to unwrap it in some way.
When you change the orientation of the device, the verticalSizeClass
environment value will change and because SwiftUI is now observing it (because you are using it) the body
of your View
will automatically be re-run and the scale will change.
I went through each of my views in different orientations and on different devices, making note of any adjustments needed. For the View
above, scaling it seemed like the most logical choice to fit it all into the space and still be usable. But you have other choices:
Change the spacing between controls. I did that in another
View
and just reduced some of the white space.Change the size of fonts. You would be surprised what a slightly smaller font can do to make things fit nicely.
Re-arrange the screen as shown below.
On the left the two DatePicker
s are arranged vertically while in landscape, on the left, they are arranged horizontally.
if self.verticalSizeClass == .compact {
// arrange elements in an HStack
} else {
// arrange elements in a VStack
}
Using the size trait classes in SwiftUI is easy:
Declare the
@Environment
variable for the one(s) you want.Use a test in the layout code to determine how the UI should look based on the value,
Compact
orRegular
.
That’s all there is to it.
Localizing your SwiftUI App
Tips on making your app available in other languages.
“Localization” is the process of making your app usable in multiple languages. This is different from “internationalization” which is taking localization to the next level where you handle colors and icons in a meaningful way to the locale of the app’s user. This also includes being sensitive to the format of currency, numbers, and dates and times. Fortunately, iOS does some of this for you - if you have used the right APIs. For example, if you create a Date()
and then display it using DateFormatter
with DateStyle.short
, iOS will see to it that the date reads correctly in the device locale (eg, 7/28/2020 in the United States and 28/7/2020 anywhere else in the world).
Xcode isn’t exactly as friendly as Android Studio when it comes to making your English-only (hard-coded strings) code ready for localization, so my post here shows you one way to handle this. There is a program called genstrings
that can help, but I am not covering that here.
It is helpful to pick a second language to start with. You can use British English but the differences aren’t as obvious as say using Dutch, so I will go with that.
Project Step
You will need a file that contains the original - English for myself - strings you want to be available in other languages.
Use Xcode’s File->New->File
menu command and in the template selector, pick Strings File
in the Resources
section. Name the file Localizable.strings
for this example (it can be any name you want). The file will be empty; you will add content to it below.
String Extension
Next make an extension to the String class to make some usages easier, which will make more sense a bit later in this post. For now, create a new Swift file called Strings+Extensions.swift
and put this into it:
extension String {
func localized() -> String {
return NSLocalizedString(self, comment: self)
}}
Extraction Step
Open the English version of Localizable.strings
and put it into is own Window (or vertically split the Xcode editor so that the strings file is in one half the other half you can use for source code). Open one of your files that contains hard-coded strings. For example:
Button(“Close”) { … }
In the Localizable.strings
file, add the line:
”close-button” = “Close”;
Note that both sides of the equal sign (=) are in double-quotes and the line ends with a semi-colon (;). This format is very important and Xcode will flag it as an error if the formatting is not correct.
Back in the source code, replace ”Close”
with ”close-button”
which is what is on the left side of the equal sign in the Localizable.strings
file.
Button(“close-button”) { … }
I use identifiers for the string key codes (the left side) rather than the English text, but you could also have used
”Close” = “Close”
in the localization strings file. Some people prefer the source code to read with the original strings. I find using codes makes it easier to spot missing translations.
Let’s say you have this in your code:
var defaultAddress = “Unknown Street”
You add ”default-address” = “Unknown Street”
to the Localizable.strings
file and then replace the code:
var defaultAddress = “unknown-street”
When you run the app, the default address will be “unknown-street”! What happened to the localization? The Button shows up as “Close” and not “close-button”.
This is because most SwiftUI components, like Button
and Text
not only take String
arguments but LocalizedStringKey
arguments as well. In other words, when you pass ”close-button”
to the Button
initializer, SwiftUI looks to see if that string is a localization key and if so, uses what it finds in the Localizable.strings
file; if not, it uses the string as passed.
In the case of defaultAddress
, you want to initialize it like this:
var defaultAddress = “unknown-street”.localized()
That String extension I added above comes in handy to quickly add code to programmatically switch to the localized version. The down-side is that if you use a code like I do, if you forget to put that code (or misspell it) into the Localizable.strings
file, the app will display the code at runtime. Which is why a lot of people use the English string as their code and not the way I do it. But that’s just my preference.
Localize
Now that you have all of the English code/value pairs in the Localizable.strings
file, it’s time to prepare it for translation. In the Project Navigator, select the Localizable.strings
file, then open the File Inspector (⌥+⌘+1). Tap the Localize
button.
This will create the English localization for this file and create a directory in your project called en.lproj
(you can see it with Finder).
Now open your project file from the Project Navigator (make sure your project is selected and not the target) and open the Localizations
section of the Info
tab. You will see English - Development Language
.
Tap on the Plus (+)
button and pick your languages. I picked Dutch.
A dialog opens for you to select the resources to localize. For SwiftUI you can uncheck LaunchScreen.storyboard
and just localize Localizable.strings
.
Once you have done that, look at the Project Navigator and you will see the Localizable.strings
entry is now folder with the different language files in them.
Translation Step
Unless you know people who speak the languages you are going to use (or you a native speaker - yeah for you!), you will find Google Translate to be your new best friend.
What I did was open Google Translate in new browser window and set it aside. Then I open the Localizable.strings
file for the language I’m working on. Let’s say Dutch in this case.
If you did the
Localizable.strings
file for English before creating new localizations like I suggest in the steps above, Xcode will copy all of the English strings into the Dutch file for you - saving you a lot of time.
Now all you need to do is copy the English phrase to the Google Translate window where it will automatically get translated, then copy it back and paste it into your Localizable.strings
file for that language.
Go ahead and translate all of the strings.
As good as Google Translate it, it may not be perfect. It is best to get someone who knows the target language well to proof read your app. Sometimes the context will change which word to use and you do not want to offend anyone!
Testing it Out
First, run your app in a simulator to make sure you do not see any string code keys (eg close-button
) showing up. If you do, make sure you put the correct key in the Swift code and it is spelled correctly (“closed-button” is different from “close-button” as is “Close-Button”).
Now you want to make sure the localization works and it’s pretty easy to do that.
In Xcode, edit the current schema (you can also create a new one, even one per language):
In the schema editor, change the Application Language
and Application Region
drop-downs. Here I’ve changed them to “Dutch” and “Netherlands”.
Now run your app. When it appears in the Simulator, it will behave as if it in the Netherlands and you should see all of the strings you changed now in Dutch!
One More Thing
Let’s say you are writing a SwiftUI view. For example, something that displays a product title. You might write it like this:
struct ProductTitle: View {
let label: String
let title: String
var body: some View {
HStack {
Text(label)
Spacer()
Text(title)
}
}
}
Now you want to use this new view and pass it different labels which you have put into the Localizable.strings
files:
VStack {
ProductTitle(label: “primary-label”, title: product.primary)
ProductTitle(label: “secondary-label”, title: product.subtitle)
}
When you run this, you do not get your localized text, but instead you see the code words (eg, “primary-label”). That’s weird, because the string you are just passing directly to a SwiftUI Text
view so it should work, right?
No, because the Text
view has multiple initializers. It has one which takes a String
and one which takes a LocalizedStringKey
. You passed it a String
.
So you could simply do:
ProductTitle(label: “primary-label”.localized(), title: product.primary)
but that’s kind of messy. A better approach would be to change the data type of label
inside of ProductTitle
to:
let label: LocalizedStringKey
and now the data types match what you want. When you run your app, you will see the localized strings as you expect. This is a little more versatile in that you can also pass it a string that is not a localization key.
Summary
So there you have it. Create a Localizable.strings
file with ”key-code”=“value”;
pairs (do not forget the semi-colon), use Google Translate to do the translations for you, and test it out by editing the runtime schema (or create new ones).
Een fijne dag verder and have fun and take the world by storm!
Drive-In App
A 21st century American drive-in movie experience.
Going to the drive-in as a kid was always a fun experience. I remember my Uncle getting me and my cousins into his Chevy with the bench seats and going to the drive-in. We’d get there and hook the speaker box onto the car door window then us kids would run down to the concession to buy YooHoo, hotdogs, and popcorn. The movie would start and the speaker would crackle to life, its tinny sound making its way into the car. My Uncle would shhh us kids so we could hear it.
Today, in the midst of a pandemic, the American drive-in is having a bit of a renaissance as musicians are giving concerts to cars and movies are being played again. I even read that Walmart is going to covert some of its parking lots into drive-in theaters. So I wondered what the drive-in experience is like today and imagined this little app to make it a much more 21st century experience.
Imagine if you will, an app that runs on your phone and in your car via Apple CarPlay or Android Audio. You use your phone app to order the tickets and present them on your way into the theater’s arena. You pick a spot next to a pylon with the space number and tap your phone against it, registering your location. The app knows which theater you are at using GPS.
Now you reach for your car’s infotainment screen and activate the in-car drive-in app. This app connects to the drive-in’s system and syncs up with it. Instead of that awful window speaker, the movie plays over your car’s multi-speaker system, giving you probably the best movie sound you have ever experienced. Not only that, the in-car app can display closed captioning and functions as an ordering system for the concession which can deliver your YooHoo, hotdogs, and popcorn right to your car.
So imagine nestling into your car’s seats, reclining as much as you please, enjoying massive sound, eating traditional snacks, and enjoying the American Drive-In experience.
The phone app lets you purchase tickets, arrange food delivery upon arrival, and, if your car is not Apple CarPlay or Android Auto capable, a way to transmit the movie’s sound to your car’s speakers via bluetooth.
The parking spot pylons at the drive-in provide WiFi hot-spots as well as electric car charging stations.
The CarPlay/Auto app provides closed captioning, surround sound through your car’s speakers, and a way to order food for delivery.
I don’t have the resources to make this app, and who knows, maybe by the time it would be finished and tested and ready to roll out, the pandemic would be over. But I think we may be missing something about piling the kids into the car and heading off into the night to enjoy a show under the stars.
Thanks for reading and indulging in my app fantasy from yesteryear.
Adventures with React Native
Some considerations for you if you are thinking about using React Native.
The promise of React Native
The goal of React Native is to answer a high-tech Holy Grail: Write Once, Run Everywhere. And by and large, that is true, at least for iOS and Android which are the only platforms I used with it.
My exposure to React Native (RN, henceforth) is limited. I am not a professional RN developer and I do not know all of the ins and outs of using it. But the 6 months I spent with it were interesting. I started at a small company as the new (and only) mobile developer. I took over the RN mobile app someone else had written. They wanted some new features and to see if its performance could be improved. I was hired for my iOS and Android experience because the CTO thought the RN application should be scraped and re-written natively for iOS and Android. I just had to make some improvements before I could begin the re-write.
Their app uses a complex data set, real-time data feeds (via WebSocket), maps, lists, barcode scanning, and some other things. The data can be just a few hundred items or it could be thousands.
React Native apps are mostly written in JavaScript (the native parts are written in the platform’s code - Objective C or Java - and then bridged into the JavaScript). When you start a RN project you have RN generate the actual platform-specific application which forms a container to host your “application” (JavaScript) code. Its essentially a JavaScript interpreter that uses the native bridge to get components to appear and input to be received. For all that it does, its actually quite fast. But remember, your application’s code is not being run directly on the hardware, it is being interpreted (well, translated to byte code, then that’s run) within a virtual machine.
In some ways, React Native is like Android itself, which runs on a variety of processors. Your one Android application (in Kotlin or Java) is executed in a Java Virtual Machine which as been built specifically for the hardware of the device.
The company’s app’s performance problem stemmed from the very fact of RN’s existence: the code is not run optimally for the hardware. Imagine downloading 2,000 items and then rendering them onto the map. Then moving the map around, zooming in and out, etc. Very very slow. Plus there were lots of graphics going on. It was just a performance mess.
Getting Started
I mentioned above that when you start a React Native app you have RN generate the application shell - the actual native application which runs on the device and hosts your JavaScript app code. That’s true, but there’s more to the story.
When you write an iOS or an Android app, you start off by getting the respective IDE: Xcode for iOS and Android Studio for Android. That’s it. Download those, make a quick test app, run it, and start building. You may need some more complex software that you can purchase or find for free (like a barcode scanner) if you do not want to take the time to build it yourself (which, in these environments, is always an option).
When you want to start off with React Native you need a small army of new programs: brew
, npm
, node.js
to name a few. That plus React Native itself. If you just recently upgraded your macOS, you may find the versions of these haven’t quite been upgraded to match, but generally these are pretty solid.
Once you get React Native to generate its shell program you’ll find your directory divided into two parts: one for iOS and one for Android. Inside the iOS directory is a real iOS workspace and project. Go ahead and open that. What you’ll find will be a surprise. This is a very large app (after all, its a full blown advanced JavaScript interpreter with code to host and bridge to native modules). But what I found the most surprising, and the first disappointment, were the nearly 900 compiler warnings. Most deprecation warnings, but also syntactic irregularities. And it was all Objective C. It made me wonder if anyone was actually working on this app full time to remove those because, to me, compiler warnings are not show stoppers, but they should be addressed. I like delivering apps without warnings if at all possible.
True or False
When you build a RN application you run into a lot of things you need. For example, we needed a barcode scanner and access to the camera for both the barcode and so the user could take photos. After doing some digging I discovered this entire world of React Native developers. Basically, if you need to do something in your React Native app, someone has probably already written a plugin to do that. For this article, I’ll focus on the barcode scanner module, but what I’ll describe happened with a couple of modules.
I found a couple of barcode scanner modules for React Native. One thing to look for is the platforms they cover; sometimes the author only supports one platform. When I found one that looked promising I created a new separate RN app to test it out. Good modules come with complete instructions: how to incorporate the module into your code (for Android, change the gradle.build
file, for iOS change the project info.plist
for instance or some are even simpler). Some modules leave it up to the interested reader to figure out the installation.
I cannot stress enough how grateful I am for stackoverflow.com
; a troupe of heroes.
Once I got the module running in a test application and understood how to use it, I replicated the installation into the main application and hooked it up. That worked for the most part EXCEPT in this situation: The company’s app already existed which means its React Native directory/codebase was generated months earlier before I started - it was all in git
for me to just clone locally. My test RN app was recently created. I was using a newer version of a RN app in my test than was being used in the company’s app. In other words, version incompatibilities.
I had to tinker with the code from the barcode scanner module to make it compatible with the RN application code for the main app. Most 3rd party apps come with their source code, but it was the wrapper code to fit it into the RN environment that was the cause of the problem.
This brings me to the actual heart of this article: upgrading.
Upgrading
During the course of my involvement with the company’s original RN app - and early on in the involvement - I accidentally let my computer upgrade Xcode (from 9 to 10 at the time). I didn’t think much of that until I tried to run the app. This began a journey into a land of frustration like no other I have experienced in my years of writing software. Were I a better writer, I could craft for you an Orwellian tale to make you lose a few nights of sleep. But I am not, so I will keep this as brief as possible.
When Xcode upgraded it also upgraded the iOS SDK which brought with it some deprecations but also a few out and out changes - you know, when the deprecated code is finally dropped.
The React Native version used to build the app used some of that now defunct code. Which meant it failed to build. After searching on stackoverflow.com
I found a couple of workarounds: update to a newer version of React Native or go into your RN code and change it. Now keep in mind that this is code that is generated and could be replaced at any time should you need to rebuild the directories; you really should not need to edit it.
I was able to make the changes to the RN code and move on. But that only lasted a few minutes because several of the many (many) 3rd Party modules used to build the app also had similar problems. One fix for one of them was to just get the newest version of that module. In my naiveté I did that.
This started a chain reaction of updating modules because module A now didn’t like the dependency on module B which was now incompatible with iOS - I had to upgrade React Native. To do this you change a few control files, erase all of the modules and re-get them (ie, all that work trying to upgrade them by hand goes out the window) and then re-generate the React Native shell application.
Your React Native app may turn out to be highly dependent on community software, written and, hopefully, maintained by people who are often not being paid full time to write these modules. They may have written them to do their own work and donated them or are just hobbyists.
Now as it happens, some of the 3rd party RN plugin modules were no longer being supported and thus, not compatible with the new React Native code. So while some modules were just fine, others were non-functional. For those I had to find newer replacements (recurse to the above section).
The bottom line here: Upgrading your OS or IDE can open a days-long can of worms with React Native. You find 3rd Party modules cannot be upgraded or they are not supported or the authors have intentions to update too, but just don’t have the time yet to do that.
Hello Simulator? It’s Me
Earlier I mentioned you run your app on device simulators (or emulators for Android). You can also run them on real devices. This is all great - when it works. Remember that upgrade process? Well, iOS upgrades also change the simulators. More important - they change the location or name of the simulators. When you go to run your RN app, there are scripts that run which hunt down the simulator you want and launch it. When the Xcode 10 update came through, the names of the iOS simulators changed and even the latest version of RN that I upgraded to had no clue where these simulators were.
So again, back to stackoverflow.com
for the answer: edit the RN execution script that finds the simulators and change it so it detects the simulators. And that was fine for a while until another update to Xcode ended that and I had to go back and change the script again. Keep in mind that should I have had to update React Native again, I would have had to change this script.
Debugging
When you use an IDE on a native application, you just set a break point right in the code and launch the app. The app runs until it hits a break point then you can examine the current state, etc.
You cannot easily do this with React Native. And of course, there are several ways to get debugging to work. The easiest one I found was to open Chrome
and attach it to the JVM running inside the iOS simulator (I could not get it work with an Android emulator). You could then set a break point in the JavaScript code and most of the time it would work. Sometimes (like 40% of the time) it would break inside minified code which is always fun.
There is a React program you can use but I never had much luck with that. I think it was more suited to web-based React than React Native.
The starting up of the debugger (you had to get the incantation just right or it would not work), the attachment to the process, the running of the React Native mobile environment, hoping your break points were still there (often you have to reset them), was just another frustration.
Thoughts
At this point you are probably thinking I am not a fan of React Native. And you’d be mostly correct. Following my experience with RN, I got to re-write the company’s app natively for iOS and Android. For Android I chose Kotlin rather than Java and for iOS I went with SwiftUI since it was just out and looked super cool - PLUS - it is a reactive framework and that is one thing I really liked about React. In fact, I liked the state flow so much I used a Kotlin version - ReKotlin
- in the Android app.
Oh - and I stuck with iOS for this blog post, but I also had similar issues when it came to Android and updates to gradle
.
The promise of React Native: Write Once, Run Everywhere, holds true to a point. And that point is upgrading. Once your app has been written for a while, along comes an OS update and an IDE update. This can send you into a tailspin. You have React Native core code that becomes unusable. You have 3rd Party modules that are incompatible with newer version of RN itself. At one point I thought it was hopeless because it was a vicious cycle of changes.
My final take away for you is this: if you use React Native, understand that for long haul, its an investment. I see the appeal as I wrote the same app twice for different platforms. If there is a problem I may have to fix it twice. But the upgrades are easier and the app is way, way, faster. I like Kotlin and Swift far more than I like JavaScript, which is just a personal preference here. So for me, the tradeoff of a single code base versus multiple code bases is worth the effort. Bonus if your company has both iOS and Android developers!
Custom Binding with SwiftUI
Use a custom binding to get more control over the data flow.
A couple of days ago I was looking at some SwiftUI questions and saw one from a fellow trying to store the value of a picker into some Core Data. I thought I would share my solution here. Two caveats:
This is for SwiftUI 1.0 - the person asking the question was using SwiftUI 2.0 (in beta as of this writing), but I think my solution will still work.
This solution is not something uniquely mine - you will see other people mention it in their posts and writing. I thought I would highlight it specifically.
Here’s the problem: you want to use a component (DatePicker
in this case) which transfers the value selected by the user via a Binding. If you are coming from UIKit thinking, your instinct is to use a delegate. Very understandable but that isn’t going to work for SwiftUI. The way to use the picker is:
private @State var selectedDate = Date()
…
DatePicker(
selection: self.$selectedDate,
displayedComponents: [.date]) {
EmptyView()
}.labelsHidden()
When the user changes any of the wheels of the DatePicker
the value of selectedDate
is immediately changed.
The question asked was: How can the value (selectedDate
) be stored into Core Data? More generically, how do you react to this choice made by the user?
If you wanted the UI to change when the user picked a date, you can set that up easily using an IF
statement and SwiftUI will detect that selectedDate
changed, run the body
code again, execute your IF
statement, and produce a new View
which it with then use to change the screen. That’s pretty straightforward. But what if you want to do something non-UI with the value when its changed?
The solution is to use a custom binding. Let’s keep selectedDate
as the backing store variable so it can be used elsewhere and add a new var
which reacts to the DatePicker
changing its selection in a custom way:
private var handleBinding: Binding<Date> {
Binding(
get: { self.selectedDate },
set: { (newValue) in
self.selectedDate = newValue
// do something with newValue, like call another function
// or store it with Core Data or fetch some remote data})}
and then put this to use:
DatePicker(
selection: self.handleBinding,
displayedComponents: [.date]) {
EmptyView()
}.labelsHidden()
The @State
variable that was used in the binding with the DatePicker
is replaced with the custom binding, handleBinding
. It works exactly the same, except when the DatePicker
’s selected date changes, the handleBinding
set
function is called, setting the @State
variable and then doing whatever else you want it to do.
You can of course, use custom binding with your own components. If you component has a @Binding var
in it, you can pass a custom binding. This will give you more control over the flow of data in your SwiftUI app, just don’t abuse it and write sloppy code. Use it only when you need to and try to keep your code clean and readable.
GIT Merge & Squash
A short and sweet summary of using git merge
Over the course of my career I’ve encountered many source code control systems as I’m sure many of you have. It seems softwarekind has reached the point where we have whittled all of the contenders down to just a few with git
becoming the most popular (at least that’s my understanding). One of git
’s virtues is its ability to do branching - where you make a copy of your work, make changes, and either toss it away if its crap (and return to your previous revision) or keep your changes and move on to the next task.
The focus of this article is about one of my favorite features of git
. If you are a seasoned git
user you can skip this but if you are starting out and want a couple of pointers, then please join me. There are a lot of git
commands and each has a myriad options. I am only discussing the git merge
command and its squash
option. And even with that I’m not going into high detail, mostly because I don’t think it’s necessary to be productive.
Each company’s development environment is different and each has its own rules and workflow. You may find what I write in this article to not fit with your company’s culture, which is fine of course. I think this process that I use is simple and straightforward. It follows closely the standard “git
flow” process which is just a series of steps to follow when developing code and using git
on a daily basis.
Let’s assume you have a working directory with your source files in it and are on a develop
branch. This would be the code that, when built, runs your application with all of the latest features. At this moment in time you are in sync with everyone else on the project.
This is where things can be different from your company. Some places work directly on the master branch, others work on a release number branch, others work on a shared develop branch, which is what I am assuming.
You are tasked to do some new work - some sort of feature. To do this you create a branch. The naming of your branch is, again, a company culture thing. If your company wants you to always push your branch to the remote repository, then its wise to name your feature with a directory so use git checkout -b
features/new_search
and that is the name I will use.
If you do git status
it should show that you have a clean working directory (no changes) and you are on the features/new_search
branch. Terrific. So now you can make your changes.
You make some changes over the course of the next few hours, running the code, making sure it works. But the feature isn’t complete; it might take a few more days. You could just walk away for the day, but I recommend that, if you are at a point where you are happy with the code, you commit it to your branch. This way your next changes can be discarded if you go down the wrong path and you won’t need to worry about corrupting something you have working. I believe this is essential and the safest thing you can do. There is nothing more frustrating to have some nicely working code, then spend another hour on the next step and screw it up. If you do commit your code, you can just discard your changes and start over.
This process of moving forward, doing a commit, making more changes, a commit, continues until you have the new_search
feature working and tested. You may have made just a single commit or maybe a dozen commits.
At this point you are done with the feature and now its time to merge your changes into the develop
branch. This is what I do:
I make sure all of my changes are committed to my branch (
features/new_search
).I
git checkout develop
which replaces my working directory (and feature code) with the version of the application I had a few days ago. This may not be the latest version of thedevelop
branch.To bring my feature into the
develop
branch, I do:git merge features/new_search —squash
. Remember that you might have many commits on your feature branch. The-squash
option removes all of your commits on your branch and reduces all of your changes to a single change (per file). For example, let’s say you have File A and you made changes: ‘apple’ (commit) ‘orange’ (commit) ‘banana’ (commit). The-squash
reduces this to ‘apple’ -> ‘banana’. Without the -squash
thedevelop
branch would have all of your commits listed; with-squash
thedevelop
branch will just have a single commit, which is the next step.I commit my changes to the
develop
branch usinggit commit -m “Added the New Search feature”
. When you look at the commits todevelop
you will see just one commit for your feature.I do two last things to finish up: I
git push
mydevelop
branch to the remote repository andgit branch -d features/new_search
which deletes the branch locally. I do not keep extraneous branches around as I find it confusing later on.
Using -squash
is something some companies may frown upon because it removes all of the history of the changes. But without it, your repository is full of minor commits. How many times have you gone through your code, think its fine, do the commit, then realize you forgot to remove some comments or print statements and have to make another commit? If those minor commits are on your branch and you -squash
your merge, you do not carry those over. It is a matter of taste, but think by and large, keeping your repository free from miscellaneous changes makes a better repository.
Just a quick jump back to step 2 above. If you are working in a team, there is a good chance that while you have been working on your feature branch, other people have also been working on their features. So before you merge your feature branch into the develop
branch, you should pull down any new changes with git pull
. Then merge and squash your changes.
The merge and squash after doing a pull
should be clean unless your changes also touch files someone else changed. In that case the merge will fail and you have to fix the changes yourself. There are many resources on how best to that along with many programs to help you. Basically you resolve whether to keep your changes or keep the others’ (aka “theirs”) changes.
Be sure to follow your company’s policy on this. Some places will require you to run a bunch of tests before pushing your develop
branch; other places have automated this and run tests when a push happens.
I hope you find this light and easy explanation of get merge —squash
helpful. I find keeping my repository neat and tidy is very rewarding.
A Year of SwiftUI
At WWDC 2019 (that’s last year), Apple introduced an amazing new UI framework - SwiftUI
. Its introduction was (for me at least) on par with the announcement of Swift itself. I’d like to take you through my adventure with SwiftUI - version 1 - to show what you’ve missed and to hopefully, prepare you for Swift 2.0
Reactions
I had recently been working with React Native and was planning to re-write the app for iOS. This was well after WWDC 2019, so I had already heard of SwiftUI. My work with React Native was important in that I was already in the “reactive” frame of mind. That is, I worked with a UI whose display was state driven and bound tightly with the state. If you aren’t familiar with reactive programming here is a quick snapshot:
Your UI is composed of controls whose content (or appearance) is tied to a value in the component’s state. For example, a label whose’s
text
property is the value ofstate.amount
. Whenever you changeamount
in the state, the UI automatically refreshes with the updated value. In other words, you do not programmatically assign the label an updated value; instead, the label draws its value from the state. Or, the UI reacts to changes in the state. Clever, huh?
Having been thinking along those lines, I started looking into SwiftUI. Imagine my surprise at seeing @State
and talk about the UI reacting to changes in the state. Apple had gone done their own version of reactive programming! And it wasn’t just a little nod toward it - it was full-fledged deep end.
SwiftUI is only part of the new offering. Along with updates to Swift itself (which are crucial to making SwiftUI syntax so easy) is the
Combine
framework. Combine is what allows@State
to work and enables the Observer pattern to be so easily incorporated into your apps.
So this was going to be the new way forward to develop iOS apps. OK, that’s what I was going to do with this React Native re-written app: SwiftUI 100%.
There were a lot of bumps and challenges along the way. And you can read challenges as hair-pulling and doubt as to whether this was the right decision or not.
First off, I knew SwiftUI did not fully replace UIKit. I knew I had to write integration code - Apple’s own tutorials to get you started with SwiftUI did that. For example, the app would need to use MapKit and MKMapView
was not a SwiftUI element. Fortunately Apple was prepared for this and provided a way to wrap UIKit components so that they would appear to be SwiftUI elements. Pretty neat actually.
Secondly, I had to really look at problems differently. How do I set up the UI and its state so that when values change the right parts of the UI change? How do I receive new values from the remote service and get the UI to reflect those new values? How I put up a date chooser? How can I make scrolling through a 2000 element list faster? The challenges just kept coming.
A Model Year
You may be familiar with the “massive view controller” problem. This is where you pack everything and the kitchen sink into a single UIViewController file. You put access to your data, manipulations for that data, formatting that data, etc. all into the file whose real job is to get the UIView to display. It is easy to fall prey to this, especially as you are flushing out ideas or doing prototyping.
And this exactly what I started do with SwiftUI. I wasn’t concerned at first with separation of concerns - I was more interested in understanding how SwiftUI worked. But in forgoing this design pattern, I actually missed a key part of how SwiftUI works. What happened was that I was trying to get the screen to see changes the code was making, but they weren’t showing up.
I took a step back and realized that I was neglecting a very powerful concept in SwiftUI - the model. It’s pretty simple: you put your data into a class that has functions to manipulate it and then make the UI observe changes to it.
SwiftUI provides ObservableObject
for this purpose; it’s part of Combine. When you make a class Observable, you can select properties to be @Published
which sets up the observer pattern and all the code needed to watch for changes.
I pulled a lot of code out the UI classes and into models. I wound up with lots of models - essentially one per “screen” with some go-betweens. This allowed me to just set up the binding between the UI and the data in the model, have code - like remote server call handlers - update the appropriate models which would then automatically trigger the UI to change. Voila - an app!
Summary
As often as I questioned my decision to use SwiftUI, I just as often determined it was the right path. Apple was going to make this its de facto way to write apps. If you wanted to be in the lead position and wanted to take advantage any new stuff, you needed to be with SwiftUI.
And look what happed at WWDC 2020: Widgets and App Clips. You write those in SwiftUI. And - maybe even more important - cross device deployment. Your app can run on an Apple Watch, iPhone, iPad, Apple TV, and macOS - one app. SwiftUI’s runtime makes sure your app looks the best for the device and behaves appropriately. I’m sure there’s some tweaking you do in the app to actually make that happen, but Apple’s done all the heavy lifting for you - IF you use SwiftUI.
A lot of folks have been afraid to take the plunge, citing the old “SwiftUI is 1.0 and will change or is buggy.” Yeah that was true. So now you’ve got SwiftUI 2.0 on the horizon - do you want to be a leader or do you want to hang back and eat dust?