It’s quite simple to add TouchBar UI to your macOS app in Xamarin.Forms.
In this example we add three controls:
- Image: App icon
- Image: Cover
- TextField: Artist – Track – Album
In AppDelegate.cs we setup our TouchBar after the LoadApplication()
method:
public void SetupTouchBar() { NSApplication.SharedApplication.SetAutomaticCustomizeTouchBarMenuItemEnabled(true); var touchBarDelegate = new TouchBarDelegate(); var touchBar = new NSTouchBar() { Delegate = touchBarDelegate, }; int count = 3; string[] ids = new string[count]; for (int i = 0; i < count; ++i) { ids[i] = i.ToString(); } touchBar.DefaultItemIdentifiers = ids; window.SetTouchBar(touchBar); }
In this case the items are static with count 3
.
Our TouchBarDelegate We give back a TouchBarItem for the index.
using System; using AppKit; using Foundation; using Xamarin.Forms; using Xamarin.Forms.Platform.MacOS; namespace Cuterdio.macOS { internal class TouchBarDelegate : NSTouchBarDelegate { public override NSTouchBarItem MakeItem(NSTouchBar touchBar, string identifier) { switch (identifier) { case "0": return GetImage(identifier); case "1": return GetImage(identifier); case "2": return GetTextField(identifier); default: throw new NotImplementedException(); } } private NSTouchBarItem GetImage(string identifier) { NSImage image = null; if (identifier == "0") { // App Icon image = NSImage.ImageNamed(NSImageName.ApplicationIcon); } else { // Album if (!string.IsNullOrEmpty(App.PlayerPage.ViewModel.ImageUrlBackground)) { try { NSUrl url = new NSUrl(App.PlayerPage.ViewModel.ImageUrlBackground); image = new NSImage(url); image.Size = new CoreGraphics.CGSize(30, 30); } catch { return null; } } } if (image == null) { return null; } NSCustomTouchBarItem item = new NSCustomTouchBarItem(identifier); var imageView = new NSImageView(); imageView.Image = image; item.View = imageView; return item; } private static NSTouchBarItem GetTextField(string identifier) { NSTextField textField = new NSTextField(); textField.TextColor = Color.White.ToNSColor(); textField.Alignment = NSTextAlignment.Left; string value; if (string.IsNullOrEmpty(App.PlayerPage.ViewModel.Artist)) { value = "📻 " + App.PlayerPage.ViewModel.Station; } else { value = "🎙 " + App.PlayerPage.ViewModel.Artist; if (!string.IsNullOrEmpty(App.PlayerPage.ViewModel.Track)) { value = value + " 🎸 " + App.PlayerPage.ViewModel.Track; } if (!string.IsNullOrEmpty(App.PlayerPage.ViewModel.Album)) { value = value + " 💿 " + App.PlayerPage.ViewModel.Album; } value = value + " 📻 " + App.PlayerPage.ViewModel.Station; } if (value == null) { return null; } textField.StringValue = value; NSCustomTouchBarItem item = new NSCustomTouchBarItem(identifier); item.View = textField; return item; } } }
You can see it’s strait forward und emojis are a easy solution without dealing with images.