Introduction
This blog post will explain how we can create MAC applications using the Xamarin.Forms App.
Let's start by adding a Cocoa project in our existing xamarin.Forms Project.
- Open Visual Studio
- Click On new project.
- Click On App under the MAC section as shown in the image above.
- Add Cocoa Project.
- Now Install Xamarin.Forms Package in your cocoa Application making sure it has the same version other projects are referring to.
- Add a reference to your PCL project to your cocoa project.
- Open Info.Plist in textEditor and Remove the source entry NSMainStoryboardFile.
- Now Open the AppDelegate class of your cocoa application.
- Change the AppDelegate derived from NSApplicationDelegate to Xamarin.Forms.Platform.MacOS.FormsApplicationDelegate.
- Go to DidFinishLaunching function of app Delegate and add below 2 lines
- Xamarin.Forms.Forms.Init();
- LoadApplication(new App());
So now our DidFinishLaunching looks like
- public override void DidFinishLaunching(NSNotification notification)
- {
- Xamarin.Forms.Forms.Init();
- LoadApplication(new App());
- base.DidFinishLaunching(notification);
- }
In AppDelegate constructor we need to create a new window which will be returned from main window property of AppDelegate()
- public AppDelegate()
- {
- var style = NSWindowStyle.Closable | NSWindowStyle.Resizable | NSWindowStyle.Titled;
- var rect = new CoreGraphics.CGRect(200, 1000, 1024, 768);
- window = new NSWindow(rect, style, NSBackingStore.Buffered, false);
- window.Title = "Xamarin.Forms on Mac!";
- window.TitleVisibility = NSWindowTitleVisibility.Visible;
-
- }
Goto Main.cs and add
NSApplication.SharedApplication.Delegate = new AppDelegate();
Main.cs Looks Like.
static void Main(string[] args)
{
NSApplication.Init();
NSApplication.SharedApplication.Delegate = new AppDelegate(); // add this line
NSApplication.Main(args);
}
Now we just need to set our cocoa application as a startup project and run it. The output should look like:
So we have successfully created and executed our first Xamarin.Forms MAC Application.
Happy Coding :)