Touch Bar in SwiftUI + PoweredTouchBar

Pavel Kasila
3 min readMar 22, 2021
Just an example of the Touch Bar using PoweredTouchBar

When you search for any documentation on using the Touch Bar in SwiftUI, you will see documentation for SwiftUI’s touchBar modifier which is the simplest way to use the Touch Bar on macOS with SwiftUI. But there is one problem with it: everything you add into touchBar modifier will be shown on the Touch Bar through NSHostingView, so if you want just to add a button, then your button will not be NSButtonTouchBarItem, but NSHostingView rendering this button.

Buttons done using touchBar modifier
UI hierarchy when using SwiftUI

As you can see there is a blue background when you are trying to create these buttons. Let’s find out why. The reason for this is that when you are using SwiftUI’s touchBar modifier, it will create this enormous amount of elements in UI hierarchy to render these buttons. There are even multiple NSHostingViews in here. So, basically it's really strange behavior. Actually this code is a similar code from WWDC19 session “SwiftUI on All Devices” just using TextEditor instead of Text and also I’ve added padding and imageScale to make it look more like buttons not just something weird. Also, you will understand the problem with this huge amount of elements in UI hierarchy in 3D mode, just compare SwiftUI’s TouchBar and NSTouchBarItem.

UI hierarchy in 3D mode

What did I want?

Actually, I wanted a way to use NSTouchBarItems in SwiftUI, so I haven’t found any solutions to this problem and have decided to develop my own library to deal with this problem, I’ve called it simply PoweredTouchBar.

Buttons done with PoweredTouchBar

This library lets you use the Touch Bar in SwiftUI more effectively and use NSTouchBarItems in your SwiftUI app by using available PoweredTouchBarButton, PoweredNSTouchBarItem and PoweredTouchBarCustomItem, so you can create buttons (more to come) or use any NSTouchBarItem or NSView to create any item for the Touch Bar.

So, there is a simple example of how to create simple buttons using PoweredTouchBar:

What you will get with the code above

Conclusion

In conclusion, I just want to thank you for reading this story until the bottom. So, if you want to support me, then you can help me working on this project by creating issues, contributing your code or anything else. If you have discovered any bugs or want a new feature, then add your issue on GitHub. Also, you can support me by donating me on Patreon.

--

--

Pavel Kasila

Just a 18 year old boy, who codes whatever he wants.