Dissecting SemanticMerge, Part 4: Cocoa 101 for WinForms/WPF developers

Monday, March 24, 2014 45 Comments

Ever thought about writing a Mac GUI in C#?

You’re probably used to Buttons, Panels, Dialogs and the like, but how do they map to the Mac counterparts?

Well, this is what we try to cover in this post: a Cocoa 101 for WinForms developers.


Mac development is a new world for a Windows developer. New tools, new subsystems, new OS, new languages...

We wanted to develop a Mac native UI for SemanticMerge and then we faced some decisions: stay in C#? Move to Objective-C? Get used to the Interface Builder or ignore it?

Since other teams might be facing a similar situation we thought it would be good to dissect our SemanticMerge GUI and use it to explain some Mac GUI development essentials.

Before entering the Cocoa 101 we had to decide whether we should go for Objective-C or not and whether we should go for a native UI or try something like Qt.

In a previous post we also covered some MonoMac basics and then one interesting topic: should you use the Interface Builder or go hard-core and code the entire GUI?

Welcome to Cocoa

You start and write your first “hello world” in Xamarin Studio but then you’ve to figure out how to really structure your app. And then is when worlds collide.

As Windows developers we were used to Buttons, Forms, Panels, Splitters and all but… that’s not the same thing when you get to Xamarin.Mac. You’ve to get used to the Cocoa and a new set of controls.

As I mentioned first, this is what I’m going to do by dissecting our SemanticMerge application. And for the sake of simplicity, I’ll start with a simple dialog, the start up window:

And let’s now go and dissect it:

The picture shows all the controls we use in this simple dialog and I think it is a good way to get familiar with Cocoa if you come from a Windows background.

Let me share thoughts on the picture above:

  • The Window has a ContentView which is the one you’ll use to place more controls inside. The ContentView is an NSView.
  • The NSBoxes are somehow similar to Panels in WinForms. You can use them to contain other controls.
  • Buttons: all buttons in Cocoa will be of type NSButton, but then you’ll set properties to it depending on the style of the button you want to use.
  • Something similar happens with NSTextField: you can use a TextField as a WinForms TextBox, but you can also configure it to be like a Label. In the picture I defined the ‘edit boxes’ as NSTextFields with “Editable = true” and “Bordered = true”.

Alignment with Constraints

Once you meet a few controls is time to know how to align them. You can always just place them in the Window ContentView with global coordinates, but it won’t help if you need your NSBoxes to grow with the window, or your buttons to keep aligned to the right.

While we were all familiar with Anchors in WinForms, to code UIs in Mac we need to learn the Constraints.

Constraints are the set of rules you use to define where each control is located, aligned and so on.

The ‘language’ to define constrains can be intimidating at first, but it is really easy to learn and very powerful.

I’ll first explain how constraints are defined and later I’ll cover how to code it in C#.

Let’s start with a very simple scenario: just a window with two buttons as the figure shows:

If we don’t set the constraints correctly (step 2) then when the window grows the buttons will stay on the same position, losing the correct relative position “anchored” to the bottom right of the window.

In step 3 the constraints are correctly set and the buttons keep the relative position to the bottom right.

How do we achieve this? With the ‘magic of Mac constraint rules’.

The rule to specify the horizontal alignment is very simple:

  • H: stands for horizontal rule.
  • [cancel(150)] refers to the “cancel” button (later I’ll explain how do you tell the system that the button will be named ‘cancel’ when specifying contraints.
  • -10- means you’re separating the two buttons with a “10 size” separation.
  • [ok(150)] gives a 150 size to the “ok” button.
  • -10- is another separator.
  • | the last vertical bar on a horizontal constraint rule refers to the right border of the window. It is the piece of the constraint saying “keep everything aligned to the right”.

The language is easy to remember and very powerful as you can see.

Since we’re only specifying the “right border” it means everything will be relative to the right.

Notice I didn’t set a “left bar” which means the buttons will be ‘anchored’ to the right.

What if I edit the rule and modify it in the following way:

“H: |-10-[cancel(150)]-10-[ok]-10-|”

I have added a “left border” so basically I’m saying:

  • The “cancel” button should be linked to the left border with a 10 points margin.
  • Then there will be another “10” separator between the buttons.
  • And the “ok” button will grow as much as it needs in order to keep a right margin of 10 with the right border.

The result will be something like:

Now that we know how to set up the horizontal constraints, the vertical ones will be really easy to figure out:

We specify 2 different rules where we set the vertical margin between the buttons and the bottom border of the window, and also the button height (or vertical size).

Now that we “master” the constraints, it is not hard to figure out the layout of the SemanticMerge launch window:

Remark: you ALWAYS have to specify both the vertical and horizontal constraints. Otherwise nothing will be rendered. It happened to us :-)

Defining constraints in C# and MonoMac

Now that the constraint language is crystal clear ;-): how is this set on a MonoMac application?

Look at the following code listing which is able to create a Window like the following:

    public override void AwakeFromNib ()
        base.AwakeFromNib ();

        // button created programatically
        NSButton button = new NSButton();
        button.Title = "Click Me";

        // button added to the window
        NSView contentView = Window.ContentView;

        // now we set the constraints

        // nothing works if you do not specify this!!
        button.TranslatesAutoresizingMaskIntoConstraints = false;

        // now let's add the names of the controls
        // to the constraints system so we can
        // reference the controls by name in the
        // constraints rules

        var views = new NSMutableDictionary();
        var constraints = new List();

        views.Add(new NSString("button"), button);

        // and here go the constraints

                "H:[button(150)]-10-|", 0 , null, views));
                "V:[button(23)]-10-|", 0, null, views));


Setting the constraints in code is straightforward as you see, but simply don’t forget to:

  • Specify horizontal and vertical constraints.
  • Set the “TranslatesAutoresizingMaskIntoConstraints” to false!

Wrapping up

We’ve discussed about whether going native or use multi-platform UI toolkits, then we went through the ‘imperative vs designer based’ UI implementation alternatives and later we introduced some very common Cocoa controls.

Finally we dissected the “launcher dialog” in SemanticMerge to explain how constraints work.

Hope you find this post useful and happy Mac C# hacking.

We develop Plastic SCM, a version control that excels in branching and merging, can deal with huge projects and big binary assets natively, and it comes with GUIs and tools to make everything simpler.

If you want to give it a try, download it from here.

We are also the developers of SemanticMerge, and the gmaster Git client.


Unknown said...

I learn how to design a form and merge with the other from this post. Images are very useful to understand the functions. iOS Event App Online

David Smith said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Online Training from India. or learn thru ASP.NET Essential Training Online . Nowadays Dot Net has tons of job opportunities on various vertical industry.
JavaScript Online Training from India

IT said...
priya said...

I likable the posts and offbeat format you've got here! I’d wish many thanks for sharing your expertise and also the time it took to post!!
Data Science Training in Chennai
Data Science course in anna nagar
Data Science course in chennai
Data science course in Bangalore
Data Science course in marathahalli
Data science course in bangalore

Maria said...

There was a time when it was difficult with money. I decided to turn to gambling for all kinds of slot machines and the like. Now knowing this site splendid best internet casino across and opposite to me is no longer scary

Raj Kumar said...

Great post! I am actually getting ready to across this information, is very helpful my friend. Also great blog here with all of the valuable information you have. Keep up the good work you are doing here.
Advertising Agency
3d Animation Services
Branding services
Web Design Services in Chennai
Advertising Company in Chennai

Rj Shiyam said...

Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here.
Are You looking for best online courses and free webniars you just click following links
Online Certificate Courses
Machine Learning Online Courses
Best Online Certificate Courses In India
Online Courses On Digital Marketing
Online It Courses In India

Rajesh Anbu said...
kishore said...
offpageseo70 said...

Nice blog,I understood the topic very clearly,And want to study more like this.
Data Scientist Course

dhishageetha said...
Anonymous said...

Thanks for sharing information. Choosing computer accessories from leading IT store offer great discount and value for your money Computer Store Australia | All in One Pc Australia

It's truly an honor to run across informational content like this. You are clearly knowledgeable on this topic and you have unique views to share.
Best Data Science training in Mumbai

Data Science training in Mumbai

Cool stuff you have and you keep overhaul every one of us

data science course

Thanks for sharing information post. Limousine King offers affordable limo hire Melbourne that make your accosion special. Wedding Car HireLimo Hire Melbourne prices

I agree with a lot of the points you made in this article. I appreciate the work you have put into this and hope you continue writing on this subject.
SAP training in Kolkata
Best SAP training in Kolkata
SAP training institute in Kolkata

This material makes for great reading. It's full of useful information that's interesting,well-presented and easy to understand. I like articles that are well done.
SAP training in Mumbai
Best SAP training in Mumbai
SAP training institute Mumbai

Avijit said...

So far, I agree with you on much of the info you have written here. I will have to think some on it, but overall this is a wonderful article.

SEO services in kolkata
Best SEO services in kolkata
SEO company in kolkata
Best SEO company in kolkata
Top SEO company in kolkata
Top SEO services in kolkata
SEO services in India
SEO copmany in India

Nice Blog. Here are some good profile of educational sites.

Best college for mba International Business in Dehradun

eazyclasses said...

You must have a lot of pride in writing quality content. I'm impressed with the amount of solid information you have written in your article. I hope to read more.
SAP training in Kolkata
SAP training Kolkata
Best SAP training in Kolkata
SAP course in Kolkata
SAP training institute Kolkata

SEObuckett said...

Amazing information. All of the points mentioned by you is really important.

SEO company in kolkata

Avijit said...

After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article.
Data Science Institute in Bangalore

If your looking for Online Illinois license plate sticker renewals then you have need to come to the right place.We offer the fastest Illinois license plate sticker renewals in the state.
Data Science Course in Bangalore

I recently came across your article and have been reading along. I want to express my admiration of your writing skill and ability to make readers read from the beginning to the end. I would like to read newer posts and to share my thoughts with you.
Data Science Training in Bangalore

Programs said...

Nice blog. I finally found great post here Very interesting to read this article and very pleased to find this site. Great work!
Data Science Training in Pune
Data Science Course in Pune

Priyanka said...

Attend The Data Analyst Course From ExcelR. Practical Data Analyst Course Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analyst Course.
Data Analyst Course

sathishkumar said...
priyanka said...

Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
Correlation vs Covariance
Simple linear regression
data science interview questions

surya said...
sathya said...

I must thank you for the efforts you have put in penning this site. I am hoping to check out the same high-grade content by you later on as well. Keep up the good work

selenium training in chennai

selenium training in chennai

selenium online training in chennai

selenium training in bangalore

selenium training in hyderabad

selenium training in coimbatore

selenium online training

lavanya said...

Thanks for sharing an informative blog keep rocking bring more details.I like the helpful info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite sure I will learn much new stuff right here! Good luck for the next!Java training in Chennai

Java Online training in Chennai

Java Course in Chennai

Best JAVA Training Institutes in Chennai

Java training in Bangalore

Java training in Hyderabad

Java Training in Coimbatore

Java Training

Java Online Training

I'm not one of those readers that comments on articles often, but yours really compelled me. There's a lot of interesting content in this article that is interesting and bold.
Data Science training in Mumbai
Data Science course in Mumbai
SAP training in Mumbai

Your writing style says a lot about who you are and in my opinion I'd have to say you're insightful. This article reflects many of my own thoughts on this subject. You are truly unique.
SAP training in Kolkata
SAP training Kolkata
Best SAP training in Kolkata
SAP course in Kolkata

harshni said...
anand said...
360digiTMG said...

Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.
python course training in guduvanchery

ramesh said...

Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome
Wonderful article.It is to define the concepts very well.Clearly explain the information.It has more valuable information for encourage me to achieve my career goal

Azure Training in Chennai

Azure Training in Bangalore

Azure Training in Hyderabad

Azure Training in Pune

Azure Training | microsoft azure certification | Azure Online Training Course

Azure Online Training

What incredible writing is this! Totally amazed by such views that you have put into this content. It really made me brood over the topic.
SAP training in Mumbai
SAP course in Mumbai

I must mention that it was worthy enough to take my time to go through the points made in this amazing article. I am amazed by the way you have described the topic
SAP training in Kolkata
SAP course in kolkata

aravind said...

This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.Really you have done great job,There are may person searching about that now they will find enough resources by your post.
DevOps Training in Chennai

DevOps Online Training in Chennai

DevOps Training in Bangalore

DevOps Training in Hyderabad

DevOps Training in Coimbatore

DevOps Training

DevOps Online Training