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

Monday, March 24, 2014 91 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.

Background

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;
        contentView.AddSubview(button);

        // 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

        constraints.AddRange(
            NSLayoutConstraint.FromVisualFormat(
                "H:[button(150)]-10-|", 0 , null, views));
        constraints.AddRange(
            NSLayoutConstraint.FromVisualFormat(
                "V:[button(23)]-10-|", 0, null, views));

        contentView.AddConstraints(constraints.ToArray());
    }

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.

91 comments:

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

dhinesh said...

Excellent Blog! I would Thanks for sharing this wonderful content.its very useful to us.This is incredible,I feel really happy to have seen your webpage.I gained many unknown information, the way you have clearly explained is really fantastic.keep posting such useful information.
Full Stack Training in Chennai | Certification | Online Training Course
Full Stack Training in Bangalore | Certification | Online Training Course

Full Stack Training in Hyderabad | Certification | Online Training Course
Full Stack Developer Training in Chennai | Mean Stack Developer Training in Chennai
Full Stack Training

Full Stack Online Training


Rashika said...

Fantastic article I ought to say and thanks to the info. Instruction is absolutely a sticky topic. But remains one of the top issues of the time. I love your article and look forward to more.
Data Science Training Institute in Bangalore

Nice to be seeing your site once again, it's been weeks for me. This article which ive been waited for so long. I need this guide to complete my mission inside the school, and it's same issue together along with your essay. Thanks, pleasant share.
Best Data Science Courses In Bangalore

Nice to be seeing your site once again, it's been weeks for me. This article which ive been waited for so long. I need this guide to complete my mission inside the school, and it's same issue together along with your essay. Thanks, pleasant share.
Best Data Science Courses In Bangalore

devi said...

Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites!
Data Science Training In Chennai

Data Science Online Training In Chennai

Data Science Training In Bangalore

Data Science Training In Hyderabad

Data Science Training In Coimbatore

Data Science Training

Data Science Online Training

I'd love to thank you for the efforts you've made in composing this post. I hope the same best work out of you later on too. I wished to thank you with this particular sites! Thank you for sharing. Fantastic sites!
360DigiTMG Data Science Course

This is a great post. This post gives a truly quality information. I am certainly going to look into it. Really very helpful tips are supplied here. Thank you so much. Keep up the great works
360DigiTMG Data Science Training

swaroop said...
swaroop said...

very nice blogs!!! i have to learning for lot of information for this sites...Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.

Web Designing Training in Chennai

Web Designing Course in Chennai

Web Designing Training in Bangalore

Web Designing Course in Bangalore

Web Designing Training in Hyderabad

Web Designing Course in Hyderabad

Web Designing Training in Coimbatore

Web Designing Training

Web Designing Online Training

Maneesha said...

Set aside me effort to peruse all the comments, yet I truly appreciated the article. It end up being Very useful to me and I am certain to all the analysts here! It's consistently pleasant when you can not exclusively be educated, yet in addition engaged!
360DigiTMG data science institute in hyderabad

Outstanding blog appreciating your endless efforts in coming up with an extraordinary content. Which perhaps motivates the readers to feel excited in grasping the subject easily. This obviously makes every readers to thank the blogger and hope the similar creative content in future too.

360DigiTMG Data Analytics Course

Revathi said...
prabhu said...

I like the helpful info you supply in your articles. I’ll bookmark your weblog and take a look at once more here regularly. I am relatively certain I will learn a lot of new stuff right here! Good luck for the following!
IELTS Coaching in chennai

German Classes in Chennai

GRE Coaching Classes in Chennai

TOEFL Coaching in Chennai

spoken english classes in chennai | Communication training


vivekvedha said...
radhika 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.



AWS Course in Bangalore

AWS Course in Hyderabad

AWS Course in Coimbatore

AWS Course

AWS Certification Course

AWS Certification Training

AWS Online Training

AWS Training

John Mitani said...

Excellent article.

network infrastructure

best said...

Duties like managing a blog, developing and managing digital marketing campaigns to raise brand awareness, tracking conversion rates and making improvements to the website, designing strategies to drive traffic to the company website, utilising techniques including paid search, SEO and PPC. digital marketing course in hyderabad

360digiTMG said...

I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.
360DigiTMG

Thanks for the lovely blog. It helped me a lot. I'm glad I found this blog. Thanks for sharing with us, I too am always learning something new from your post.

360DigiTMG Business Analytics Course in Bangalore

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.You can also check my articles as well.

360DigiTMG Data Science Course In Pune
360DigiTMG Data Science Training In Pune

Thank you..

I just found this blog and hope it continues. Keep up the great work, it's hard to find good ones. I added to my favorites. Thank you.

360DigiTMG Data Analytics Course in Bangalore

Duties like managing a blog, developing and managing digital marketing campaigns to raise brand awareness, tracking conversion rates and making improvements to the website, designing strategies to drive traffic to the company website, utilising techniques including paid search, SEO and PPC.
"digital marketing course in hyderabad"

It is a great pleasure to read your message. It's full of information I'm looking for and love to post a comment that says "The content of your post is amazing". Excellent work.

Artificial Intelligence Course in Bangalore

I'm highly dazed with the quality of the content which you have penned down. This is a splendid article! Your article has all the necessary information on the respective topic.
SAP training in Kolkata
SAP training Kolkata
Best SAP training in Kolkata
SAP course in Kolkata

hyder31 said...

I sent your articles links to all my contacts and they all adore it including me.
UI/UX designers

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.You can also check my articles as well.

360DigiTMG Data Science Course In Pune
360DigiTMG Data Science Training In Pune

Thank you..

I looked at some very important and to maintain the length of the strength you are looking for on your website
data science courses in delhi

hyder31 said...
TrustAllys said...

I have the same thoughts on much of this material. I am glad I'm not the only person who thinks this way. You have really written an excellent quality article here. Thank you very much.


IT Security Assessment services

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.You can also check my articles as well.

Data Science Course In Hyderabad
Data Science Training In Hyderabad
Best Data Science Course In Hyderabad

Thank you..

travel5212 said...

Amazing Article,Really useful information to all So, I hope you will share more information to be check and share here.thanks for sharing .
website: Cycling tours package

Top quality article with very informative information and found very knowledgeable thanks for sharing waiting for next blog.
Data Analytics Course Online

Excellent blog with very impressive writing and unique content, information shared was very valuable and useful thanks for sharing.
Data Science Course in Hyderabad

centre99 said...

it is really a great and helpful piece of info. I am glad that you shared this helpful information with us. Please keep us informed like this. Thank you for sharing.
apply for malaysia visa

riya singh said...

I enjoyed over read your blog post. This was actually what i was looking for and i am glad to came here!
Website: Imitation jewellery

Nice Information Your first-class knowledge of this great job can become a suitable foundation for these people. I did some research on the subject and found that almost everyone will agree with your blog.
Cyber Security Course in Bangalore

Anu said...

Thanks for sharing this, I actually appreciate you taking the time to share with everybody.
Data Science Training In Hyderabad

Writing in style and getting good compliments on the article is hard enough, to be honest, but you did it so calmly and with such a great feeling and got the job done. This item is owned with style and I give it a nice compliment. Better!
Cyber Security Training in Bangalore

I have to search sites with relevant information ,This is a
wonderful blog,These type of blog keeps the users interest in
the website, i am impressed. thank you.
Data Science Course in Bangalore

Great article with valuable information found very resourceful thanks for sharing.
typeerror nonetype object is not subscriptable

I have to search sites with relevant information ,This is a
wonderful blog,These type of blog keeps the users interest in
the website, i am impressed. thank you.
Data Science Training in Bangalore