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

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

274 comments:

«Oldest   ‹Older   201 – 274 of 274   Newer›   Newest»
Scottishkilt said...

Great article! This is the type of information that are meant to
be shared across the internet. Thank you for sharing such a useful post. Very Interesting Post! I regularly follow this kind of Blog.
irish flute store

princika said...

I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
data science course fees in bangalore

Awesome article. I enjoyed reading your articles. this can be really a good scan for me. wanting forward to reading new articles. maintain the nice work!
Data Science Courses in Bangalore

AI Courses said...

What an incredible message this is. Truly one of the best posts I have ever seen in my life. Wow, keep it up.
AI Courses in Bangalore

I am sure it will help many people. Keep up the good work. It's very compelling and I enjoyed browsing the entire blog.
Business Analytics Course in Bangalore

Download Cricket Mazza 11 for Android Live Line & Fastest IPL Score. Get Live Cricket Scores, Scorecard, Commentary, Match Info and Schedules of All International & Domestic Matches, Series wise Stats, Records, Analysis and Facts, Trending News and Tweets, Recent ICC Player and Team Rankings. Also Download best cricket game apps for ios, including Beach Cricket, Cricket T20 Fever 3D, Download Real Cricket mazza 11 and other top answers suggested and ranked.

Download Cricket Mazza 11 for Android Live Line & Fastest IPL Score. Get Live Cricket Scores, Scorecard, Commentary, Match Info and Schedules of All International & Domestic Matches, Series wise Stats, Records, Analysis and Facts, Trending News and Tweets, Recent ICC Player and Team Rankings. Also Download best cricket game apps for ios, including Beach Cricket, Cricket T20 Fever 3D, Download Real Cricket mazza 11 and other top answers suggested and ranked.

yaraplas said...

Buy Telegram Post Views adsmember
buy cheap telegram members adsmember will help you to grow your business with https://adsmember.com/

Mallela said...

Thanks for posting the best information and the blog is very important.artificial intelligence course in hyderabad

Fantastic website! I'd want to express my gratitude for the time and effort you put into producing this article. I expect the same level of excellence from you in the future. I wanted to express my gratitude for the excellent website! Thank you for sharing your knowledge.

digital marketing training in hyderabad
digital marketing course in ameerpet
digital marketing course training in hyderabad ameerpet
digital marketing online training in hyderabad
digital marketing course in hyderabad
digital marketing course training in hyderabad
digital marketing course with internship in hyderabad
digital marketing training institute in hyderabad
digital marketing course in hyderabad ameerpet

Unknown said...

I just stumbled upon your blog and it was great to be here! Definitely, this is a great post with great content.
Website - https://jbms.in/

Unknown said...

I enjoyed this blog. It's an informative topic. Keep up the good work, I am surely going to come back to this site in future.
Website - https://jbmsmartstart.in/

Unknown said...

Great article Lot's of information to Read...Great Man Keep Posting and updating People. Thanks!!
Website - https://steppingstone.school/

Good information you shared. keep posting.
data science course in aurangabad

Thanks for Sharing this Valuable Information with us: this is very useful for me. Keep it Up.
ai course

princika said...

I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
data science training in chennai

Excellent Blog! I would like to thank you for the efforts you have made in writing this post. Gained lots of knowledge.
Data Analytics Course

AI Courses said...

What an incredible message this is. Truly one of the best posts I have ever seen in my life. Wow, keep it up.
AI Courses in Bangalore

Awesome article. I enjoyed reading your articles. this can be really a good scan for me. wanting forward to reading new articles. maintain the nice work!
Data Science Courses in Bangalore

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..
machine learning training in aurangabad

I am sure it will help many people. Keep up the good work. It's very compelling and I enjoyed browsing the entire blog.
Business Analytics Course in Bangalore

You have completed certain reliable points there. I did some research on the subject and found that almost everyone will agree with your blog.

Data Science Training in Bangalore

I have voiced some of the posts on your website now, and I really like your blogging style. I added it to my list of favorite blogging sites and will be back soon ...

Digital Marketing Training in Bangalore

I wanted to leave a little comment to support you and wish you the best of luck. We wish you the best of luck in all of your blogging endeavors.

Artificial Intelligence Training in Bangalore

The Extraordinary blog went amazed by the content that they have developed in a very descriptive manner. This type of content surely ensures the participants explore themselves. Hope you deliver the same near the future as well. Gratitude to the blogger for the efforts.

Machine Learning Course in Bangalore

Just pure brilliance from you here. I have never expected something less than this from you and you have not disappointed me at all. I suppose you will keep the quality work going on.
data scientist training in hyderabad

Good to be here in your article or post, whatever, I think I should also work hard for my own website like I see some good and updated working in your site.
data scientist course in hyderabad

data science said...



Great to become visiting your weblog once more, it has been a very long time for me. Pleasantly this article i've been sat tight fosuch a long time. I will require this post to add up to my task in the school, and it has identical subject along with your review. Much appreciated, great offer. data science course in nagpur

Imon Kearns said...

Sankey diagram is a very useful visualization to show the flow of data. ChartExpo provides you a better and easiest way to create the Sankey Diagram in no time without coding only on few clicks. Read more here : Sankey Diagram in Excel

Priya Rathod said...

Thanks for providing a useful article containing valuable information.
DevOps Training in Hyderabad
DevOps Course in Hyderabad

mikeroads said...

Thanks for sharing the valuable information and i am glad to discover this page i really liked each part and also bookmarked you for new information on your site.
13377x
flixanity
technology write for us
tamilrockers proxy
how to install nordvpn on router
openload.co/pair
top youtube competitors
snapseed app download for pc
okta advanced server access

We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work
digital marketing courses in hyderabad with placement

jane smith said...

Hiya very cool web site!! Man ...Superb .. I’ll bookmark your site and take the feeds additionally?
McAfee is quick and easy to install.
McAfee programming gives the digital security services to ensure your hardware information.Install mcafee from mcafee.com/activate |
How to Uninstall or disable McAfee WebAdvisor ?
How do I get a free trial of McAfee
Disable antimalware service executable
Why do you need McAfee Security ?

jane smith said...

Keep yourself secure with McAfee security .
McAfee activate on your computer.
Use McAfee Antivirus Plus on your computer.
Why McAfee Internet Security is important?

jane smith said...

It's really a nice and useful piece of info.
Setup your ms office from office.com/setup |
What is the use of Windows 10 media creation tool
how to find How to find windows 10 product key
Do you know you can Install office without account .
How to Create Windows 10 recovery USB

jane smith said...

I look forward to fresh updates and will share this website with my Facebook group!
Find your HP printer support
Easy way for How to connect hp printer to wifi
Why is my HP printer offline
Fix your printer by printer troubleshooting
Why is my printer connected but not printing

raj said...
haritha said...

I enjoyed reading the post. Thanks for the awesome post.

Best Web designing company in Hyderabad

Best Web development company in Hyderabad

data science said...

I was basically inspecting through the web filtering for certain data and ran over your blog. I am flabbergasted by the data that you have on this blog. It shows how well you welcome this subject. Bookmarked this page, will return for extra. data science course in jaipur

i am glad to discover this page : i have to thank you for the time i spent on this especially great reading !! i really liked each part and also bookmarked you for new information on your site.
artificial intelligence training in chennai

Dubai Fun Club for luxurious Dubai Escorts and entertainment services. You can easily find the best Escorts in Dubai on our website

haritha said...

I enjoyed reading the post. Thanks for the awesome post.
Best Web designing company in Hyderabad

vivikhapnoi said...

I’m excited to uncover this page. I need to to thank you for ones time for this particularly fantastic read !! I definitely really liked every part of it and i also have you saved to fav to look at new information in your site.
giá vé máy bay từ hà nội đi moscow

bao giờ có chuyến bay từ singapore về việt nam

khi nào có chuyến bay từ canada về việt nam

khi nào có chuyến bay từ đức về việt nam

Bảng giá vé máy bay Vietjet Air tu itali ve Viet Nam

san ve may bay gia re tu Ha Lan ve Viet Nam

Data Science said...

I am glad to discover this page. I have to thank you for the time I spent on this especially great reading !! I really liked each part and also bookmarked you for new information on your site.
Data Science Training in Hyderabad


Dubai Fun Club for luxurious Dubai Escorts and entertainment services. You can easily find the best Escorts in Dubai on our website.

haritha said...

informative content. Thanks for sharing your knowledge.
Best Web designing company in Hyderabad
Best Web development company in Hyderabad

I bookmarked your website because this site contains valuable information. I am very satisfied with the quality and the presentation of the articles. Thank you so much for saving great things. I am very grateful for this site.

Data Science Training in Bangalore

I found Habit to be a transparent site, a social hub that is a conglomerate of buyers and sellers willing to offer digital advice online at a decent cost.

Artificial Intelligence Training in Bangalore

You actually make it seem like it's really easy with your acting, but I think it's something I think I would never understand. I find that too complicated and extremely broad. I look forward to your next message. I'll try to figure it out!

Machine Learning Course in Bangalore

anonymous said...

I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
data science course

Truly overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue posting. Much obliged for sharing.artificial intelligence course in chennai

Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue posting. A debt of gratitude is in order for sharing. data science institute in delhi

Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue posting. A debt of gratitude is in order for sharing. data analytics course in delhi

Unknown said...
Unknown said...
anonymous said...

I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
business analytics courses

Unknown said...

informative content. Thanks for sharing your knowledge.
Best Web designing company in Hyderabad

Unknown said...
Unknown said...
sam said...

Nice to be visiting your blog.We are the one of the certified and top-rated Riverside Chevrolet Dealership Peoria Il.
Visit here - Riverside Chevrolet Dealership

Thank you for sharing this valuable knowledge; it will be of great benefit to myself and many others. This is something I can share with my friends. Keep up to date...

digital marketing course in hyderabad
digital marketing training in hyderabad

Data Science said...

I am glad to discover this page. I have to thank you for the time I spent on this especially great reading !! I really liked each part and also bookmarked you for new information on your site.
Data Science Training in Chennai

Edison hope said...

Ah, there is a good discussion about this paragraph in this place on this website. I read all that, so now I am commenting here too... Qualified travelers to Turkey by filling an online form with their personal details can apply visa to Turkey and pay visa cost Turkey online.

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.
Web Development
Graphic Design
App Development

Data Science said...

I am glad to discover this page. I have to thank you for the time I spent on this especially great reading !! I really liked each part and also bookmarked you for new information on your site.
Data Science Course Syllabus

Virtualmindinfotech is one of the leading Top Digital Marketing Agencies in Noida sector 3, India. We provide a 360° approach to digital marketing with services ranging from search to content to social media to website design to mobile advertising. Hire us for creative website design, website development & Mobile App Design & Development services.

Lisa Kaif said...

nice blog and information to know more about oreo tv for pc please click the link

annoymous said...

I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
iot training in hyderabad

I am really enjoying reading your well written articles. I am looking forward to reading new articles. Keep up the good work.
Data Science Courses in Bangalore

I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.
Data Analytics Course

I cannot explain the perfection you have integrated into your blog post. Technologies like web app development leveraging the market with UX, contact web app development company for more.

annoymous said...

I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
business analytics courses

What an incredible message this is. Truly one of the best posts I have ever seen in my life. Wow, keep it up.
AI Courses in Bangalore

I am a new user of this site, so here I saw several articles and posts published on this site, I am more interested in some of them, will provide more information on these topics in future articles.
data science course in london

«Oldest ‹Older   201 – 274 of 274   Newer› Newest»