UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Cross-platform NS/UIViewControllerRepresentable

Forums > SwiftUI

I've got a cross-platform ViewController which exposes the same interface on both macOS and iOS, using a little bit of trickery:

#import <TargetConditionals.h>

#if TARGET_OS_OSX

#import <AppKit/AppKit.h>
typedef NSViewController NativeViewController;
typedef NSScrollView NativeScrollView;

#else

#import <UIKit/UIKit.h>
typedef UIViewController NativeViewController;
typedef UIScrollView NativeScrollView;

#endif

...

@interface FooViewController : NativeViewController

Now I'm wrapping this in UIViewControllerRepresentable and NSViewControllerRepresentable but I'm not sure if there's a way to achieve this without duplicating the code, one for macOS and one for iOS. Because the classes are so similar, the only code differences between the iOS and macOS versions are references to the types and function signatures. This kind of kills me :) Any ideas on how to improve this situation?

1      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.