Build your first MacOS app with Xamarin!

When developers think of building Xamarin apps for Apple devices, they often think of iPhone and iPad, but you can also build apps for macOS. While not exactly the same as its iOS counterpart, there are many transferable skills for iOS developers looking to build apps for macOS. With Xamarin.Mac, developers can create great macOS apps with the simplicity of C#. In this blog post, you’ll learn how to create your first macOS app in C#: a Pomodoro timer to keep us productive.

Getting Started

Building apps for macOS starts just like any other application, with File > New. Note that you’ll need to have Xamarin.Mac installed on your macOS device; building macOS apps from Visual Studio is unsupported.

File > New Solution > Mac > App > Cocoa App

Next we need to enter the app name; we’ll call this “Pomodoro.”

The Dock Item and Extension options are customizable, but for now we’ll leave them unchecked and with the blank / default values. We’ll visit these in a later blog post.

We now have our basic macOS app! You can test it by running the app from the top-left of Xamarin Studio. Unlike Xamarin.iOS, there is no need to choose a target to run the app on, since the app will run right on your Mac. You should see something like this:

Building a User Interface

Now that we have a basic macOS app, it’s time to build out our user interface; a blank app isn’t very useful!

Xamarin.Mac uses Xcode’s Interface Builder to develop UIs. Just like iOS, macOS interfaces are built using storyboards. Storyboard support on macOS was introduced in 10.10 (Yosemite). For the sake of simplicity, we’ll concentrate on macOS 10.10 and higher. If your application needs to support 10.9 or lower, you’ll need to use .xib files, which you can read more about in our working with .xib files guide.

In the solution explorer, double-click Main.storyboard. Xcode will open automatically with a “stub” project and your storyboard will open in Interface Builder.

The first thing we see is our blank UI. Notice that there’s a menu bar within the storyboard; you can use this to customize the menu bar for your app. For now, let’s leave the menu as it is.

Adding objects to our interface is somewhat similar to using the iOS designer in Xamarin Studio. On the bottom-right of the Interface Builder window, you’ll see the toolbox. You can view the available objects by selecting the icon “Show the Object library,” as shown here:

Screen Shot 2017-02-21 at 19.14.15

We can simply drag and drop the views on the view controller. To start with, let’s make an interface like the one below, which consists of a label and a button.

First, find the Label object and then drag and drop the object into our View Controller.

We can do the same for the Push Button.

To edit the label and title for the button, you can either double-click to edit the text, or, in the Attributes Inspector in the top right, find the “Title” and edit it there.

Now that we have our user interface created, it’s time to configure actions and outlets to work with the user interface in code. To do this, we need switch to the Assistant Editor, so at the top right of the main Xcode window, click the icon that looks like two overlapping circles. This should automatically bring up a file called “ViewController.h”. If it doesn’t, then, at the top of the new editor pane, click on “Automatic” and choose Manual > Pomodoro > Pomodoro > ViewController.h. Xcode should now look like this:

Setting up actions and outlets in the header file (the .h file) will allow us to reference them from our Xamarin project. To run code when the button is clicked, we need to set up an action and to reference the label from our Xamarin project, we need to set up an outlet.

Hold down the Control key, then click and drag from the button to the line beneath the final closing brace in the right editor. In the pop-up window, change the Connection to Outlet and the name to TimerLabel and hit connect:

This will automatically populate the header file with the correct definition for the outlet:

@property (nonatomic, retain) IBOutlet NSTextField *TimerLabel;

Repeat the same steps for the button, this time naming it StartStopButton.

Now we need to add the action for the button. Hold down the Control key, then click and drag as before. This time, in the pop-up window, change the Connection to Action and the name to StartStopButtonClicked and hit connect:

Once complete, you should have the following definitions:

@property (nonatomic, retain) IBOutlet NSButton *StartStopButton;
@property (nonatomic, retain) IBOutlet NSTextField *TimerLabel;
– (IBAction)StartStopButtonClicked:(id)sender;

For now, that’s all we need to do with Xcode, so you can switch back to Xamarin Studio and the changes will be synced automatically.

Adding Behavior to the UI

Back in Xamarin Studio, open the ViewController.cs file. We can now add the code for the button we set up in Xcode.

Add the following properties:

Timer MainTimer;
int TimeLeft = 1500; // 1500 seconds in 25 minutes

Then, in ViewDidLoad add the following code:

// Fire the timer once a second
MainTimer = new Timer(1000);
MainTimer.Elapsed += (sender, e) => {
TimeLeft–;
// Format the remaining time nicely for the label
TimeSpan time = TimeSpan.FromSeconds(TimeLeft);
string timeString = time.ToString(@”mm\:ss”);
InvokeOnMainThread(() => {
//We want to interact with the UI from a different thread,
// so we must invoke this change on the main thread
TimerLabel.StringValue = timeString;
});

// If 25 minutes have passed
if (TimeLeft == 0)
{
// Stop the timer and reset
MainTimer.Stop();
TimeLeft = 1500;
InvokeOnMainThread(() => {
// Reset the UI
TimerLabel.StringValue = “25:00”;
StartStopButton.Title = “Start”;
NSAlert alert = new NSAlert();
// Set the style and message text
alert.AlertStyle = NSAlertStyle.Informational;
alert.MessageText = “25 Minutes elapsed! Take a 5 minute break.”;
// Display the NSAlert from the current view
alert.BeginSheet(View.Window);
});
}
};

Xamarin lessons recordings are here!

Good evening everybody!

Lately I had the chance to keep a full day lesson about Xamarin at my University.

In case you missed the chance to attend, there’s no need to despair as all the 3 modules have been recorded and are available to watch right now!

The lessons were held on the 28th of February 2017, at Politecnico di Milano.

Introduction to C#
Slides: https://www.slideshare.net/guidomagrin/introduction-to-c-66927609

 

Introduction to Xamarin
Slides: https://www.slideshare.net/guidomagrin/introduction-to-xamarin-48120074

 

Introduction to Xamarin.Forms
Slides: https://www.slideshare.net/guidomagrin/xamarin-forms-48299949

 Happy watching! 🙂

New Xamarin tools: Xamarin Inspector!

In case you haven’t heard about it yet, it might be time to discover a new free tool, free at least while preview lasts, offered by Xamarin: the Xamarin Inspector tool! 🙂

Right from the official Xamarin blog post, that you can find here, “Xamarin Inspector is an interactive tool that you can use to diagnose and prototype changes in your application. The inspector can attach to a live application on any of the supported platforms.”

Basically, as shown in the picture below, this tool allows you to explore the UI and state of your application, alter its state, or even try new APIs on the spot.

mac-3d-view1-1024x554

If you are used to web development, you will probably love this feature.

Xamarin Inspector is available on both Windows with Visual Studio and on Mac OS X with Xamarin Studio. In order to try it you will need to jump on the alpha release channel of Xamarin. This might be not advised on your main development environment, as it might be unstable or have unwanted problems.

Happy coding 🙂

A short recap after the holiday

Good evening 😀
It was a while since the last post I was able to write for the blog, but due to the Seattle’s Imagine Cup adventures and the holiday time right after that, I lacked the material time to do so.

Before even getting into some more “hardcore” posts, I wanted to make a recap of what happened into the Xamarin house this summer.

The biggest deal was probably the availability of a Free Xamarin Subscription for any actual Windows Phone Developer. This promotion, which expired in late August, allowed any Windows Phone Developer (mainly coding in Xaml/C#) to get a free Business license and try Xamarin for free for a whole year. This surely boosted the Xamarin reach and will surely bring more and more devs to the userbase.

You can check more info about that here, still remembering that this offer expired a week ago, already:

https://blog.xamarin.com/free-xamarin-subscriptions-for-windows-phone-developers/

Also, there were a variety of Xamarin posts regarding new Office 365 Xamarin APIs and more. You can always keep yourself updated on the official blogs, which can be found at this page:

https://blog.xamarin.com/

Also, I was renewed as a Xamarin Student Partner. The program actually changed its name from Xamarin Student Ambassador.

Now that we are getting back to our everyday business, more posts and events to come.

Stay tuned! 😀

Why should I make my next mobile app in Xamarin? #Part6: Free stuff for developers!

Good morning everyone,

it was a while since the last post I wrote about the advantages involved in developing a mobile application in Xamarin, but here we are with the 6th! 🙂

Right today, Xamarin announced, through their blog, the availability for free, to each subscribed developer, of 60 minutes of Xamarin Test Cloud, per month. You can find more info about that here:

https://blog.xamarin.com/xamarin-test-cloud-now-available-to-all-xamarin-developers/

Also, about free resources (who doesn’t love free resources?) you can now try the Xamarin University for free, and take the first courses to get started with Xamarin! 🙂 Obvisouly you won’t be able to get certificated using this trial version of the University, but it might be a great chance to get started and find out if the Xamarin University is a thing for you (or not). More info about this topic here:

https://blog.xamarin.com/want-to-try-xamarin-university-now-you-can/

Last but not least, in case you are willing to start coding your first app in Xamarin.Forms, you will find this free book really useful:

http://developer.xamarin.com/guides/cross-platform/xamarin-forms/creating-mobile-apps-xamarin-forms/

It’s basically a “preview” book written by Charles Petzold which will teach you all the necessary basics to get started in Xamarin.Forms, starting from scraps.

Happy “Xamaring”! 😀

How to draw shapes in Xamarin.Forms

In case you have ever found yourself in the situation of needing to draw a shape in Xamarin.Forms, this is the library you are going to love:

https://github.com/chrispellett/Xamarin-Forms-Shape

Basically, after importing this library (with nuget) into your project, all you have to do is drawing the form you want to display. You can choose among a variety of shapes, such as Circles, Rectangles and Circle Indicators. The Circle Indicator, in particular, is an interesting control capable of displaying a two stroke width circle where the ticker bit shows the progress out of 100%).

Each shape exposes the following properties:

  • Stroke Color
  • Color (fill)
  • Stroke Width
  • Corner Radius
  • Padding

For instance, if I wanted to draw a circle with a number inside, all I have to do would be using this code:

<Grid>
<ShapeView ShapeType=”CircleIndicator” StrokeColor=”#FF21A0DB” StrokeWidth=”3″
HorizontalOptions=”Center” VerticalOptions=”Center”
WidthRequest=”200″ HeightRequest=”200″/>
<Label x:Name=”BeatLabel” Text=”200″ FontSize=”48″ FontAttributes=”Bold” BackgroundColor=”Transparent” TextColor=”White” VerticalOptions=”Center” HorizontalOptions=”Center” />
</Grid>

And, upon launching your app, the result would be:

ShapeView Circle Screen

As you can see the Circle Shape was correctly rendered, with the number in it! 🙂

On the repo of the project, you can see a comparison between how the shapes are rendered in iOS and Android:

iOS Shapes

iOS Shapes

Android Shapes

Android Shapes

Thanks for reading and…

happy coding! 😀

“Introduction to Xamarin” events are over! Let’s recap!

Good evening everybody,

it has been a while since the last time I wrote here, but I have been really busy organizing Xamarin Student Ambassadors events here in Milan!

So, what did we speak about? We had the chance to keep 3 lessons and they were articulated in this way:

  1. During the first lesson we introduced the Xamarin world and benefits, and showed how to code two apps with Xamarin, one running on iOS, the other one running on Android.
    1. Introduction Slides: http://www.slideshare.net/guidomagrin/introduction-to-xamarin-48120074
    2. Android e iOS Slides: http://1drv.ms/1EvQZ25
  2. During the second lesson we explained how to use Xamarin.Forms and how to use MVVM in Xamarin.
    1. Xamarin.Forms Slides: http://www.slideshare.net/guidomagrin/xamarin-forms-48299949
    2. Xamarin.Forms Code: https://github.com/guido1993/somecode/tree/master/Introduction%20to%20Xamarin/2nd%20Lesson%20-%20Xamarin.Forms%20Demo%20App
  3. During the third and last lesson we explained how to use SQLite into a Xamarin.Forms app, how to create Custom Renderes in Xamarin.Forms and how to implement Azure Mobile Services in a Xamarin.Forms app.
    1. SQLite Slides: http://www.slideshare.net/guidomagrin/sqlite-in-xamarinforms
    2. Azure Mobile Services Slides: http://1drv.ms/1Q8gkGh
    3. Azure Mobile Services Code: https://github.com/poz1/PoliXamarin.MobileServicesDemo

You can find the material for each lesson at the given links! I hope that all of this material will be found useful by at least someone! We will be planning more events, after summer!

See you soon, and happy coding! 🙂