C# development in MacOS with MonoMac - getting started

Thursday, July 11, 2013 , 0 Comments

During the last month I've been involved in the development of SemanticMerge for Linux.

Since we're basically a Mono shop we decided to go for GTK# and it was really a great experience. I mean, probably GTK GUIs are not the greatest ones but from the developer point of view it is extremely easy to get used to the fundamentals and start solving problems.

I read the ZetCode gtk-sharp tutorial which is really, really easy to understand and includes almost all the information you need to go with GTK.

There is also a good text about GTK titled Foundations of GTK development where you can basically find anything that wasn't covered by the tutorial. And, anyway, it is really easy to map from the pure GTK concepts to gtksharp.

Jumping to MacOS

And then is when I crashed into reality... We wanted to do something similar for MacOS, sticking to Mono/C#. After all the simplicity of HBox, VBox, Alignment... well, just placing a simple button programatically became a nightmare...

I tried MonoMac but I was totally lost. Placing buttons statically on windows was sorta fine but as soon as you tried to do some sort of dynamically alignment... well, I was lost.

Until today when we received a very explanatory email from Jérémie Laval which finally help us understand how AutoLayout works! :-)

So I'm going to share, step by step, how to develop simple things with MonoMac which will hopefully help other programmers.

A very simple Auto Layout example

Suppose you want to have a button on a Window so that it grows when the window grows but always keeping an horizontal and vertical margin like the figure below:

And here goes the code:

       public override void AwakeFromNib ()
       {
            NSView contentView = Window.ContentView;

            NSButton button = new NSButton();
            button.Title = "add";
            button.TranslatesAutoresizingMaskIntoConstraints = false;

            contentView.AddSubview(button);

            var views = new NSDictionary ("button", button);
            var constraints = new List();

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

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

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

Enjoy!

0 comentarios: