Contribute Your Storyboard Files for Humanity

Ok, ok, not quite for humanity.

We are trying to improve our support for Xamarin Studio integration with Storyboard files, and we would like to collect a bunch of different samples.

If you can share your .storyboard file with us, please email alan at xamarin.com just the .storyboard file

Posted on 11 Mar 2013 by Miguel de Icaza

Using Instruments to profile Mac apps built with Mono

On most platforms, Mono generates code dynamically as your software runs. The Instruments profiler does not have the ability to map a memory address of the generated code back to the name of your function being executed. This makes it pretty hard to find the hot spots in your code, or the bit of code responsible for a memory leak.

To solve this problem, you can use Mono's ahead of time compiler to precompile your code to native code. This will improve startup performance and also give you symbols in stack traces in Instruments.

To do this, run mono with the --aot flag over all of the assemblies that your project uses. This is the script that I ran to precompile all of my system libraries:

cd /mono/lib/mono
for i in `find gac -name '*dll'` */mscorlib.dll; do
   mono --aot $i
done

This precompiles all of the assemblies from the Global Assembly Cache (GAC) and also takes care of all of my mscorlib libraries (these are not loaded from the GAC).

Then you need to add your own software:

	 $ mono --aot bin/Debug/*.{exe,dll}

Now, when you use Instruments, you will get nice symbolic stack traces for your process.

Thanks to Alan McGovern for showing me this trick.

Posted on 03 Jan 2013 by Miguel de Icaza

Translating Objective-C adopts-protocol idioms to C#

Sometimes when looking at Objective-C samples, you might run into code that adopts protocols and you wonder how to port that code to C#. It typically looks like this:

@interface TransparentOverlay : UIView <UITableViewDelegate, UITableViewDataSource>
{
}

The above means that the "TransparentOverlay" object subclasses UIView and adopts two protocols: UITableViewDataSource and UITableViewDelegate.

The above does not really work with MonoMac or MonoTouch, since we mapped protocols into classes. In both bindings UITableViewDelegate and UITableViewDataSource are "model" classes.

The real meat of this is that somewhere in the implementation of TransparentOverlay, a UITableView will be created, and both its delegate and its data source will be configured to point to the TransparentOverlay source, something like this:

- (void) setup
{
	myTableView = [[UITableView alloc] initWithFrame:...];
	myTableView.delegate = self;
	myTableView.dataSource = self;
}

The adopted protocol allows you to perform the assignemnt there.

The equivalent code in C# needs to create a helper class that derives from the model. This is the full implementation:

class TransparentOverlay : UIView {
    UITableView tableview;

    class MySources : UITableViewSource {
        TrasparentOverlay container;

        public MySources (TrasparentOverlay container)
        {
            this.container = container;
        }

	override void MethodOne ()
	{
            container.DoSomething ();
	}
    }

    void Setup ()
    {
        tableview = new UITableView (....);

        var mySource = new MySources (this);
        tableView.Delegate = mySource;
        tableView.DataSource = mySource;
    }
}

Note that the UITableViewSource is an aggregated version of UITableViewDataSource and UITableViewDelegate, it is just a convenience Model for a very common idiom.

As you can see, instead of using "self" to point to the "TransparentOverlay" instance, you need to make it point to the mySource instance.

The methods in MySource can get access to the content of their container by using the "container" property as illustrated by the MethodOne method.

Posted on 27 Nov 2012 by Miguel de Icaza

CoreMIDI in MonoTouch/MonoMac

This new release of MonoTouch (and MonoMac) come with our new CoreMidi bindings. In the same spirit of the work that we did for AudioToolbox and other frameworks, we created a C# bindings that follows the .NET framework guidelines for the API.

When I started these bindings, I knew close to nothing about MIDI. It is a framework that is not exactly well documented for people new to MIDI, but posts like this helped me get these bindings sorted out.

MonoTouch/MonoMac binding resembles in many ways the object-oriented bindings that developers have created to make CoreMIDI easier to digest. At its core, it is still an object oriented framework, that happens to be exposed with a fairly hostile C interface.

Our interface surfaces the underlying object oriented system with a strongly typed C# interface. Unlike the C interface that exposes a general property querying system that applies to all midi objects (MidiDevice, MidiEndpoint, MidiEntity, MidiPort), the binding ensures that only the available properties for each main class are exposed. This is a convenient way of avoiding a trip to the docs and to google to find samples.

To save developers some pain, as I developed the binding, I documented my findings in the MonoTouch.CoreMIDI documentation and added various samples to our API docs:

Our CoreMidiSample is a tiny program that replicates most of the funcionality of the MIDI sample apps, and is an easy starting point for people that want to get started with MIDI on iOS.

Interesting CoreMidi events are turned into C# events, so you can listen to changes like this:

client = new MidiClient ("CoreMidiSample MIDI CLient");
client.ObjectAdded += delegate(object sender, ObjectAddedOrRemovedEventArgs e) {
	Console.WriteLine ("Object {0} added to {1}", e.Child, e.Parent);
};
client.ObjectRemoved += delegate(object sender, ObjectAddedOrRemovedEventArgs e) {
	Console.WriteLine ("Object {0} removed to {1}", e.Child, e.Parent);
};
client.PropertyChanged += delegate(object sender, ObjectPropertyChangedEventArgs e) {
	Console.WriteLine ("Property {0} changed on {1}", e.PropertyName, e.MidiObject);
};
client.ThruConnectionsChanged += delegate {
	Console.WriteLine ("Thru connections changed");
};
client.SerialPortOwnerChanged += delegate {
	Console.WriteLine ("Serial port changed");
};

//
// Create your input and output ports
//
outputPort = client.CreateOutputPort ("CoreMidiSample Output Port");
inputPort = client.CreateInputPort ("CoreMidiSample Input Port");

// Print out packets when we receive them
inputPort.MessageReceived += delegate(object sender, MidiPacketsEventArgs e) {
    Console.WriteLine ("Got {0} packets", e.Packets.Length);
};	
	
Posted on 11 Sep 2012 by Miguel de Icaza

MonoTouch and UIKit Thread Safety

No major UI toolkit is thread safe.

This means that these toolkits are not designed to have their exposed methods be invoked by multiple threads at the same time from multiple threads. The main reason is that building thread safe toolkits is both a very hard problem and can have very complicated semantics for the consumer of the toolkit.

Developers typically use multiple threads in UI applications to offload tasks that would otherwise block the user interface. The work is offloaded to a background thread that can take as long as it wants or can perform various blocking operations like disk or network operations without affecting the interactive nature of the application.

When the background code completes its work, it queues an operation to be executed on the main thread to perform any required UI updates.

In MonoTouch and MonoMac the queuing of the operation from the background thread to the main thread is done using the InvokeOnMainThread or BeginInvokeOnMainThread methods.

The rule among toolkits is: do not access any toolkit APIs from the background thread since there is nothing in the toolkit API to defend against internal state corruption caused by multiple threads updating internals at the same time. Failure to follow this rule can lead to subtle bugs or crashes. The offending code is typically very hard to track down since the problem is timing sensitive and the corruption can vary from run to run.

Helping Developers Write Better Code

In theory, it is very easy to avoid making UIKit calls from a background thread, it only takes discipline. But some developers are not even aware that they are making UIKit calls from a background thread because their code so far has not crashed (they have been mostly luck). Another problem is that software is continuously evolving, and it is possible for developers to accidentally use UIKit APIs from a background thread during a refactoring pass, or when new features are introduced by a team members that was not aware of the clean split.

With MonoTouch 5.4 we have introduced a feature that will help you track incorrect uses of UIKit from a background thread.

Starting with this release, debug builds of your application will throw a UIKitThreadAccessException exception if you try to invoke a UIKit method from a background thread.

This is what the exception will look like:

MonoTouch.UIKit.UIKitThreadAccessException:
    UIKit Consistency error: you are calling a UIKit method that can only
    be invoked from the UI thread.

  at MonoTouch.UIKit.UIApplication.EnsureUIThread
  at MonoTouch.UIKit.UIView.get_Subviews
  at Sample.AppDelegate.m__0

This is a fabulous tool. It founds bugs in my own code within a few seconds of me using my own software. Sometimes the bug is right there for you to see, but do not notice the mistake.

The Whitelist

Over time, Apple has made some of UIKit APIs thread safe. This means that there are certain APIs that can safely be used concurrently by both the main thread and background threads. Those are documented in MonoTouch's documentation

Our list is based on what Apple has publicly documented as thread safe in different forums. It is likely that more types and methods will become thread safe in the future, and when that happens, MonoTouch will will remove the particular check for debug builds for it.

Controlling The Thread Safety Check

By default MonoTouch is configured to perform the thread checks only on debug builds of your software. If you want to have these checks performed also during release builds, you can pass the --force-thread-check to the mtouch compiler.

You might want to disable this check for a couple of reasons. You might have a big infringing codebase that is mostly working for you now, and can not afford to go fix these bugs right away. Or you could get confirmation from Apple that it is safe to call an API from a background thread. With MonoTouch, we have opted to be conservative and go by what is documented, but it is very possible that there are some APIs that are thread safe and just have not been documented as such.

You can disable the feature for debug builds by passing the --disable-thread-check flag to the compiler, or you can do this at runtime by changing the value of UIApplication.CheckForIllegalCrossThreadCalls, like this:

//
// Disable UIKit thread checks for a couple of methods
//
var previous = UIApplication.CheckForIllegalCrossThreadCalls;
UIApplication.CheckForIllegalCrossThreadCall = false;

// Perform some UIKit calls here
foo.Bar = 1;

// Restore
UIApplication.CheckForIllegalCrossThreadCalls = previous;

Adding Your Own Checks

If are building a library that wants to enforce the same kind of checks, you should call the new UIApplication.EnsureUIThread from your code to perform these checks.

Posted on 10 Sep 2012 by Miguel de Icaza

Feedback Requested: Binding NSAttributedString

As NSAttributedString plays a big role, I have been trying to figure out a way of improving the process by which NSAttributedString are created from C#.

Status Today

While we support the NSDictionary-based approach of creating the attributed needed for an attributed string, like this:

var attrs = new NSMutableDictionary () {
  { NSAttributedString.FontAttributeName,
    UIFont.FromName ("Heletica 14") },

  { NSAttributedString.ForegroundColorAttributeName,
    UIColor.Black }
};

var myString = new NSAttributedString ("Hello", attrs);

If you ignore the fact that Helvetica 14 is an uninspiring and inconsequential font, the example above is error prone.

Developers can pass a UIColor where a UIFont was required, or a number or anything else. They also have no idea what values are acceptable unless they take a trip to the documentation and find out which values are allowed, and the types of their values.

The Standard Choice

What we have historicallly in situations like this is to create a helper, strongly typed class. This allows the IDE to provide intellisense for this situation, explicitly listing the types allowed and ensuring that only the correct values are set. If we use this approach, we would introduce a new class, let us say "NSStringAttributes":

var attrs = new NSStringAttributes () {
  Font = UIFont.FromName ("Heletica 14"),
  ForegroundColor = UIColor.Black
};

var myString = new NSAttributedString ("Hello", attrs);

The only problem that I have with this approach is that now we have two classes: NSAttributedString which is the actual string with the given attribute and a class that has a name that resembles too much NSAttributedString.

My concern is not that seasoned developers would be confused between NSAttributedString and NSStringAttributes, but that developers new to the platform would rightfully ask why they need to know the differences about this.

The upside is that it follows the existing pattern in MonoTouch and MonoMac: use a strongly typed class, which internally produces the NSDictionary on demand.

Giving NSAttributedString special powers

Another option is to give NSAttributedString special powers. This would allow NSAttributedString instances to be configured like this:

var myString = new NSAttributedString ("Hello") {
  Font = UIFont.FromName ("Helvetica 14"),
  ForegroundColor = UIColor.Black
}

To support the above configuration, we would have to delay the actual creation of the NSAttributedString from the constructor time until the object is actually used.

This would allow the user to set the Font, ForegroundColor and other properties up until the point of creation. This would require the NSAttributedString type to be treated specially by the MonoTouch/MonoMac bindings.

It would also make the NSMutableAttributedString feel a bit better to use: users could make changes to the attributed string all day long, and apply changes to the various properties for the entire span of the text with a simple property value:

var myString = new NSMutableAttributedString ("Hello");

// This:
myString.AddAttribute (
	NSAttributedString.ForegroundColorAttributeName,
	UIColor.Red,
	new NSRange (0, myString.Length));

// Would become:
myString.ForegroundColor = UIColor.Red;

There are a couple of downsides with the above approach. The actual attributes used for this string configuration would not be shared across different NSAttributedStrings, so for some code patterns, you would be better off not using this syntax and instead using the NSStringAttributes class.

The other downside is that NSAttributedString properties could be set only up to the point of the string being used. Once the string is used, the values would be set in stone, and any attempt to change them would throw an exception, or issue a strongly worded message on the console.

And of course, the improved NSMutableAttributedString API improvements could be done independently of the property setters existing in the base class.

Others?

Can anyone think of other strongly typed approaches to simplify the use of NSAttributedStrings that are not listed here?

Update

Thanks for your excellent feedback! It helped us clarify what we wanted to do with the API. We are going to go with the "Standard Choice", but with a small twist.

We came to realize that NSAttributedString is just a string with attributes, but the attributes are not set in stone. It is really up to the consumer of the API to determine what the meaning of the attributes are.

We had a constructor that took a CTStringAttributes parameter which is used when you render text with CoreText.

What we are going to do is introduce a UIStringAttributes for iOS to set UIKit attributes and an NSStringAttributes for AppKit that will have the same behavior: they will be strongly typed classes that can be passed as a parameter to the NSAttributedString constructor.

So we will have basically three convenience and type safe constructors based on what you will be using the NSAttributedString with as well as the standard NSDictionary constructor for your own use:

public class NSAttributedString : NSObject {
  public NSAttributedString (string str, NSDictionary attrs);
  public NSAttributedString (string str, CTStringAttributes attrs);

  // iOS only
  public NSAttributedString (string str, UIStringAttributes attrs);

  // OSX only
  public NSAttributedString (string str, NSStringAttributes attrs);
}

We will also provide convenience "GetAttributes" methods for all platforms:

public class NSAttributedString : NSObject {
  public CTStringAttributes GetUIKitAttributes ();

  // Only on iOS
  public UIStringAttributes GetUIKitAttributes ();

  // Only on OSX
  public NSStringAttributes GetUIKitAttributes ();
}

Finally, we loved Mark Rendle's proposal of using default parameters and named parameters for C#. This actually opened our eyes to a whole new set of convenience constructors that we can use to improve both the MonoTouch and MonoMac APIs.

This comes from a Sample I was working on:

var text = new NSAttributedString (
    "Hello world",
    font: GetFont ("HoeflerText-Regular", 24.0f),
    foregroundColor: GetRandomColor (),
    backgroundColor: GetRandomColor (),
    ligatures: NSLigatureType.All, 
    kerning: 10, // Very classy!
    underlineStyle: NSUnderlineStyle.Single,
    shadow: new NSShadow () {
        ShadowColor = GetRandomColor (),
        ShadowOffset = new System.Drawing.SizeF (2, 2)
    },
    strokeWidth: 5);
#endif

The only open question is whether the parameter names in this case should be camelCase, or start with an uppercase letter (font vs Font and foregroundColor vs ForegroundColor).

The result on screen are beautiful!

Posted on 24 Aug 2012 by Miguel de Icaza

MonoMac Updates

Over the last couple of months we have been silently updating both the MonoMac APIs as well as the IDE support for it. All of the features that I talked back in March are now publicly available.

More code is now shared with the MonoTouch infrastructure, which means that every time that we improve our MonoTouch IDE support, MonoMac will be improved as well.

MonoDevelop Improvements for MonoMac

The latest version of MonoDevelop that we released contains a significant update for developers. In the past, you had to use a one-off dialog box to create packages, installers and prepare an app for AppStore distribution.

With the latest release, we have now turned these configuration options into settings that are part of the project. This means that you can now configure these based on your selected project configuration, you can automate the builds, save your settings and most importantly, you have many more options at your disposal:

MonoMac packaging settings.

Plenty of the settings that go into Info.plist are now available directly in the project settings as well as the support for maintaining your iCloud keys and sandbox requirements:

MacOS Project Settings.

We also brought the MonoTouch Info.plist editor into the IDE, this allows you to maintain your Info.plist directly from the IDE. It is also a convenient place to declare which file types your application exports and consumes:

Info.plist Editor.

New Launcher

In the past we used a shell script to start your program, the shell script would set a few environment variables and invoke Mono with your initial assembly.

We now ship a binary launcher that links with the Mono runtime and fixes several long standing issues involving application launching.

Getting the latest MonoMac

To get the latest support for MonoMac, merely download MonoDevelop 3.0.4.1 (our latest build available from monodevelop.com and you will get the entire package for Mac development.

Samples

New samples in MonoMac show how to use CoreAnimation to animate custom C# properties. Our own MacDoc sample which was supposed to be just a simple demo of WebKit, MonoMac and MonoDoc has turned into a full fledged documentation browser which is now part of our own products (MonoTouch).

Posted on 27 Jul 2012 by Miguel de Icaza

Key-Value-Observing on MonoTouch and MonoMac

This morning Andres came by IRC asking questions about Key Value Observing, and I could not point him to a blog post that would discuss the details on how to use this on C#.

Apple's Key-Value Observing document contains the basics on how to observe changes in properties done to objects.

To implement Key-Value-Observing using MonoTouch or MonoMac all you have to do is pick the object that you want to observe properties on, and invoke the "AddObserver" method.

This method takes a couple of parameters: an object that will be notified of the changes, the key-path to the property that you want to observe, the observing options and a context object (optional).

For example, to observe changes to the "bounds" property on a UIView, you can use this code:

view.AddObserver (
	observer: this, 
	keyPath:  new NSString ("bounds"), 
	options:  NSKeyValueObservingOptions.New, 
	context:  IntPtr.Zero);

In this example, I am using the C# syntax that uses the Objective-C style to highlight what we are doing, but you could just have written this as:

view.AddObserver (
	this, new NSString ("bounds"),
	NSKeyValueObservingOptions.New, IntPtr.Zero);

What the above code does is to add an observer on the "view" object, and instructs it to notify this object when the "bounds" property changes.

To receive notifications, you need to override the ObserveValue method in your class:

public override
void ObserveValue (NSString keyPath, NSObject ofObject,
			NSDictionary change, IntPtr context)
{
    var str = String.Format (
	"The {0} property on {1}, the change is: {2}",
        keyPath, ofObject, change.Description);

    label.Text = str;
    label.Frame = ComputeLabelRect ();
}

This is what the app shows if you rotate your phone:

The complete sample has been uploaded to GitHub.

Posted on 19 Apr 2012 by Miguel de Icaza

Call for Comments: Strongly Typed Notifications

I am adding support for strongly typed notifications to MonoTouch and MonoMac. The idea behind this is to take guesswork, trips to the documentation and trial and error from using notifications on iOS and MacOS.

The process is usually: (a) find the right notification; (b) look up apple docs to see when the notification is posted; (c) look up each of the keys used to retrieve the data from the dictionary.

Currently, listening to a notification for a keyboard-will-be-shown notification looks like this in MonoTouch:

void DoSomething (
	UIViewAnimationCurve curve,
	double               duration,
	RectangleF           frame)
{
	// do something with the above
}

var center = NSNotificationCenter.DefaultCenter;
center.AddObserver (UIKeyboard.WillShowNotification, PlaceKeyboard);

[...]

void PlaceKeyboard (NSNotification notification)
{
    // Get the dictionary with the interesting values:
    var dict = notification.UserInfo;

    // Extract the individual values
    var animationCurve = (UIViewAnimationCurve)
	(dict [UIKeyboard.AnimationCurveUserInfoKey] as NSNumber).Int32Value;
    double duration =
	(dict [UIKeyboard.AnimationDurationUserInfoKey] as NSNumber).DoubleValue;
    RectangleF endFrame =
	(dict [UIKeyboard.FrameEndUserInfoKey] as NSValue).RectangleFValue;

    DoSomething (animationCurve, duration, endFrame)
}

Currently we map the Objective-C constant "FooClassNameNotification" into the C# class "Foo" as the member "NameNotification" of type NSString.

What we want to do is to expose the notifications as strongly typed C# events. This will provide auto-complete support in the IDE to produce the lambdas or helper methods, auto-complete for all the possible properties of the notification, strong types for the data provided and live documentation for the values in the notification.

This means that the above code would instead be written like this:

var center = NSNotificationCenter.DefaultCenter;
center.Keyboard.WillShowNotification += PlaceKeyboard;

void PlaceKeyboard (object sender, KeyboardShownEventArgs args)
{
    DoSomething (args.AnimationCurve, args.Duration, args.EndFrame);
}

The question is where should these notifications be exposed in the API? In the example above we do this by the event "WillShowNotification" on a class "Keyboard" inside the "NSNotificationCenter". We have a few options for this.

We could host the notification in the class that defines the notification, but we would have to come up with a naming scheme to avoid the name clash with the existing NSString constant:

class UIKeyboard {
    public NSString WillShowNotification { get; }

    // replace "Notification" with the class name:
    public event EventHandler WillShowKeyboard;

    // prefix the event:
    public event EventHandler KeyboardWillShow;

    // plain, does not work on all types though:
    public event EventHandler WillShow;
}

// Consumer code would be one of:

UIKeyboard.WillShowKeyboard += handler;
UIKeyboard.KeyboardWillShow += handler;
UIKeyboard.WillShow += handler;

Another option is to add everything into NSNotificationCenter:

class NSNotificationCenter {
	// Existing implementation

    public event EventHandler UIKeyboardWillShow;

    // Another 141 events are inserted here.
}

// Consumer code would be:

NSNotificationCenter.DefaultCenter.UIKeyboardWillShow += handler;

Another option is to partition the notifications based on their natural host, this is my personal favorite, but could be harder to find with the IDE using code completion:

class NSNotificationCenter {
    public static class Keyboard {
        public static event EventHandler WillShow;
    }
}

// Consumer code would be:
NSNotificationCenter.Keyboard.WillShow += handler;

All of these proposals have one potential problem: they would all assume that all of these interesting notifications are always posted into the NSNotificationCenter.DefaultCenter.

Apple's documentation does not seem to suggest that any of the iOS notifications are posted anywhere but the DefaultCenter. I could not find on GitHub any code that would use anything but the DefaultCenter.

On MacOS the InstantMessage framework posts notifications to its own notification center. We could just bind those events to this specific NSNotificationCenter.

Thoughts?

Posted on 12 Apr 2012 by Miguel de Icaza

MonoMac Updates

We have been hard at work at improving the MonoMac API to allow .NET developers to create native Mac applications using C#, F#, IronPython or their favorite .NET language.

There are couple of goodies coming on our next release of MonoMac: our Lion support is shapping up and we have been dogfooding this ourselves with our own apps.

One of our sample apps, a simple front-end to the Mono Documentation backend is now complete enough that we are going to deprecate the Gtk+ version of it and replace it with the native version of it.

MacDoc now has several new features

Apple documentation integration: MacDoc will now download the Apple docs if they are not available and blend its contents with our documentation and replace the Objective-C samples with C# samples. Amazing!

Full text indexing: the documentation browser is using Lucene to index all of the contents and allow you to quickly find the materials that you are looking for.

Conceptual Index: in addition to the full text search, we generate a curated version of the APIs that are useful for performing search-as-you-type in the documentation browser. This is useful to find APIs by class, by method name and also by Objective-C selector. This means that you can now search for Objetive-C selectors in our documentation, and you will get the actual mapping to the C# method.

Supports Lion documents, saved state and bookmarks.

We extended the ECMA XML format so it now renders images for our docs:

The source code is available now in GitHub and will be shipping in the upcoming MonoDevelop 2.8.8 release.

Posted on 06 Mar 2012 by Miguel de Icaza

Bubbles

Recently one of our customers asked about how to implement a conversation display similar to the iOS SMS/Messages display. You can find the BubbleCell sample in our Github repository.

This is what the conversation looks like:

To implement this, I used iOS's UITableView as it already provides a lot of the functionality that we need for this. What I did was to write a custom UITableViewCell that can render bubbles with their text.

I wrote both a MonoTouch.Dialog Element that you can host in your DialogViewController as well as a custom UITableCellView which can be reused by those using UITableViews directly.

This is how you could populate the initial discussion inside MonoTouch.Dialog:

Section chat;
var root = new RootElement ("Chat Sample") {
  (chat = new Section () {
    new ChatBubble (true, "This is the text on the left, what I find fascinating about this is how many lines can fit!"),
    new ChatBubble (false, "This is some text on the right"),
    new ChatBubble (true, "Wow, you are very intense!"),
    new ChatBubble (false, "oops"),
    new ChatBubble (true, "yes"),
  })
};

And this is how you would add a new element to the conversation:

chat.Section.Add (
  new ChatBubble (false, "I want more cat facts"));

Implementation

Bubble rendering is implemented in Bubble.cs and contains both the UITableViewCell as well as the element. It follows the pattern for creating UITableViewCells that I documented before.

Each cell is made up of two views: one contains a UIImageView that paints the bubble and the other one contains the text to render inside the bubble.

This is what the two bubbles images look like:

We load these using UIImage.FromFile and then use the iOS 5.0 UIImage.CreateResizableImage method to create a UIImage that can be stretched on demand. To create the resizable image we need to tell CreateResizableImage the region of the image that can be stretched. Anything outside of the UIEdgeInset will be kept as-is:

left = bleft.CreateResizableImage (new UIEdgeInsets (10, 16, 18, 26));
right = bright.CreateResizableImage (new UIEdgeInsets (11, 11, 17, 18));

This will stretch the region highlighted in red, while rendering the external border as-is:

With the above code, the image will be rendered in a variety ways depending on the Frame that is assigned to the UIImageView that hosts our resizable UIImage:

The only remaining interesting bit in the code is to configure our UILabel properly. We want to set its BackgroundColor to UIColor.Clear to avoid painting the background in a solid color and we also specify that the text should be word-wrapped if it does not fit in a single line:

label = new UILabel (rect) {
  LineBreakMode = UILineBreakMode.WordWrap,
  Lines = 0,
  Font = font,
  BackgroundColor = UIColor.Clear
};
	

Finally in our LayoutSubViews method we must compute the proper sizes for the bubbles and the text that goes in them. I made it so the bubbles did not take the entire space in a row. Instead they take 70% of the row to give a similar effect to the rendering of the iOS messages UI. The code is pretty straight-forward:

public override void LayoutSubviews ()
{
  base.LayoutSubviews ();
  var frame = ContentView.Frame;
  var size = GetSizeForText (this, label.Text) + BubblePadding;
  imageView.Frame = new RectangleF (new PointF (isLeft ? 10 : frame.Width-size.Width-10, frame.Y), size);
  view.SetNeedsDisplay ();
  frame = imageView.Frame;
  label.Frame = new RectangleF (new PointF (frame.X + (isLeft ? 12 : 8), frame.Y + 6), size-BubblePadding);
}
	
Posted on 30 Jan 2012 by Miguel de Icaza

Styling your controls in MonoTouch on iOS 5

Starting with iOS 5 it is possible to more easily style your UIViews. Apple did this by exposing a new set of properties on most views that can be tuned. For example, to configure the TintColor of a UISlider, you would write:


var mySlider = new UISlider (rect);
mySlider.ThumbTintColor = UIColor.Red;

You can also set the color globally for all instances of UISlider, you do this by assigning the styling attributes on the special property "Appearance" from the class you want to style.

The following example shows how to set the Tint color for all UISliders:


	UISlider.Appearance.ThumbTintColor = UIColor.Red;

It is of course possible to set this on a per-view way,

The first time that you access the "Appearance" static property on a stylable class a UIAppearance proxy will be created to host the style changes that you have requested and will apply to your views.

In Objective-C the Appearance property is untyped. With MonoTouch we took a different approach, we created a strongly typed UIXxxxAppearance class for each class that supports styling. Our generated UIXxxxxAppearance class is strongly typed, which allows users to use intellisense to easily discover which properties are avaialble for styling.

We also created a hierarchy that reflects the inherited appearance properties, this is the class hierarchy for the UISLider.UISliderAppearance class:

The properties exposed by UISlider for example are:

public class UISliderAppearance {
	public virtual UIColor BackgroundColor {
		get;
		set;
	}
	public virtual UIColor MaximumTrackTintColor {
		get;
		set;
	}
	public virtual UIColor MinimumTrackTintColor {
		get;
		set;
	}
	public virtual UIColor ThumbTintColor {
		get;
		set;
	}
}

MonoTouch also introduced support for styling your controls only when they are hosted in a particular part of the hierarchy. You do this by calling the static method AppearanceWhenContainedIn which takes a variable list of types, it works like this:

var style = UISlider.AppearanceWhenContainedIn (typeof (SalesPane), typeof (ProductDetail));
style.ThumbTintColor = UIColor.Red;

In the above sample the style for the ThumbTintColor will be red, but only for the UISliders contained in ProductDetail view controllers when those view controllers are being hosted by a SalesPane view controller. Other UISliders will not be affected.

Both the Appearance static property and the AppearanceWhenContainedIn static method have been surfaced on every UIView that supports configuring its style. Both of them return strongly typed classes that derive from UIAppearance and expose the exact set of properties that can be set.

This is different from the weakly typed Objective-C API which makes it hard to discover what can be styled.

Posted on 14 Oct 2011 by Miguel de Icaza

MonoTouch 5.0 is out

Yesterday we released MonoTouch 5.0, the companion to Apple's iOS 5.0 release.

Apple tends to ship Objective-C APIs that are configured through an NSDictionary instance containing configuration keys. With MonoTouch 5.0, we continued our work to improve over NSDictionary-based bindings by creating strongly-typed versions of those APIs.

In the next couple of days, I will be sharing some of the new features in iOS 5.0 and how to take advantage of those using C#.

Meanwhile, our documentation team has produced an amazing Introduction to iOS 5.0 for C# developers and put together some samples showing how to use some of the new features in iOS 5:

  • Storyboard: shows how to use Storyboards from C# and showcases the integration between Xcode 4 and MonoDevelop 2.8
  • CoreImage: shows our bubilicious strongly-typed API for CIFilters, it is in my opinion, a huge usability upgrade over the NSDictionary-based approach.
  • iCloud: Basic iCloud use.
  • Twitter: Post new tweets and query twitter for data.
  • Newsstand: A complete sample showing how you can integrate with the new Newsstand APIs to publish your own periodicals. We wont be submitting this sample for the Apple Design Awards, but it shows how to use the framework.
Posted on 13 Oct 2011 by Miguel de Icaza

TestFlight support in MonoDevelop

We have just released for TestFlight support in MonoDevelop.

This makes it simpler for developers to deploy their Ad-Hoc builds directly to Testflight, we added a "Publish to TestFlight" option:

The first time you upload to TestFlight you must provide your authentication tokens:

And after that, the IDE takes care of the rest:

This is built on top of our enhanced IPA Packaging support in the same release.

Posted on 29 Sep 2011 by Miguel de Icaza

Sales Force app built with MonoTouch

I do not blog very often about apps built with MonoTouch, but this application is drop-dead gorgeous.

It is a tool designed to be used by the sales force of a company.

You can download the app from the Apple AppStore and try it on "demo" mode. What I love about this application is how they took advantage of UIKit and CoreAnimation to create a beautiful enterprise app. It does not stop there, they use everything iOS has to offer:

Enterprise software has a reputation for being hostile to end-users. This shows that you can create great end-user software for users in the enterprise. If you were looking for inspiration for your own enterprise apps, this is the app to look for.

Posted on 12 Aug 2011 by Miguel de Icaza
Older entries »
This is a personal web page. Things said here do not represent the position of my employer.