SwiftUI Multi-platform the Old-school Approach
I decided to write a multi-platform SwiftUI app for this winter holidays. Actually, I wanted to write a separate macOS app. But AppKit is a pain, so I soon switched to the idea of a SwiftUI multi-platform app.
I previously had a limited experience with SwiftUI only in iOS apps. And the first challenge came with List
.
I created List
from an array of items like this:
And the result I got:
iOS result was great, but the macOS version lacks separator lines.
So I modified code with Divider()
:
Which produced the next result:
MacOS version looked as I wanted but iOS was messed up.
I also wanted to add UI for deleting rows from my list. So I modified a code like this:
On iOS it resulted in beautiful swipe-to-delete behavior.
But on macOS — it did nothing. So I needed to add delete buttons for rows.
To fix both issues, I decided to add an OS check logic. The usual way of doing it was with UIDevice.current.model.
But UIDevice
is part of UIKit
, and UIKit
is not supported by macOS. And I wanted a pure SwiftUI in my app.
At this point, I remembered an OS check trick I used back in Objective-C days. The Preprocessor Directives!
It works and fits the SwiftUI style. That how’s old-school C trick saved the day.
Happy hacking holidays!