Published by ChrisNTR
Monotouch Examples
When I first played with around with iPhone development, I found the website iPhoneExamples.com a great resource for learning how to do certain things. I hope that this version of the site for Monotouch would be useful for someone.
 
iPhone Programming with MonoTouch book is out!
posted by ChrisNTR
I recently collaborated on a book on MonoTouch released by Wrox. You can purchase it over on Amazon. It contains a great introduction to MonoTouch and how to use many common features of MonoTouch including building applications for the iPad.

Miguel De Icaza kindly wrote the forword for the book and the rest of the book was co-authored with Wally, Craig, Martin Bowling and Rory. I hope you enjoy the book.

 
 
 
Download the sample project
posted by ChrisNTR
If you want to download a sample project which includes all the code found on this site then you can grab it from the GitHub Repository.

 
 
 
Logging
posted by ChrisNTR
These statements will show up in both MonoDevelop's Console window and in XCode's Organizer Console window.
var myString = "MyString";
var myFloat = 4.56f;
var myInt = 5;
Console.WriteLine(String.Format("log: {0}", myString));	
Console.WriteLine(String.Format("log: {0}", myFloat));	
Console.WriteLine(String.Format("log: {0}", myInt));

 
 
 
Display Images
posted by ChrisNTR
Display an image anywhere on the screen, without using UI Builder. You can use this for other types of views as well.
var imageRect = new RectangleF(0f, 0f, 320f, 109f); 
using (var myImage = new UIImageView(imageRect))
{	
	myImage.Image = UIImage.FromFile("myImage.png");
	myImage.Opaque = true;
	view.AddSubview(myImage);
}

 
 
 
Web View
posted by ChrisNTR
A basic UIWebView.
var webRect = new RectangleF(0f, 0f, 320f, 460f);
using (var webView = new UIWebView(webRect))
{
	webView.BackgroundColor = UIColor.White;
	var urlAddress = "http://www.google.com";
	var url = new NSUrl(urlAddress);
	var urlRequest = new NSUrlRequest(url);
	webView.LoadRequest(urlRequest);
	view.AddSubview(webView);
}

 
 
 
Display Network Indicator
posted by ChrisNTR
var app = UIApplication.SharedApplication;
app.NetworkActivityIndicatorVisible = true; 
// Set True to display, False to hide.

 
 
 
Animation: Series of images
posted by ChrisNTR
Show a series of images in succession. Make sure the images have their build action set to "Content".
List<UIImage> myImages = new List<UIImage>();
myImages.Add(UIImage.FromFile("myImage1.png"));
myImages.Add(UIImage.FromFile("myImage2.png"));
myImages.Add(UIImage.FromFile("myImage3.png"));
myImages.Add(UIImage.FromFile("myImage4.png"));
			
var myAnimatedView = new UIImageView(view.Bounds);
myAnimatedView.AnimationImages = myImages.ToArray();
myAnimatedView.AnimationDuration = 1.75; // Seconds
myAnimatedView.AnimationRepeatCount = 0; // 0 = Loops Forever
myAnimatedView.StartAnimating();
view.AddSubview(myAnimatedView);

 
 
 
Animation: Move an object
posted by ChrisNTR
Show something moving across the screen. Note: this type of animation is "fire and forget" -- you cannot obtain any information about the objects during animation (such as current position). If you need this information, you will want to animate manually using a Timer and adjusting the x&y coordinates as necessary.
var theAnimation = CABasicAnimation.FromKeyPath("transform.translation.x");
theAnimation.Duration = 1;
theAnimation.From = NSNumber.FromFloat(0f);
theAnimation.To = NSNumber.FromFloat(-60f);
exampleLabel.Layer.AddAnimation(theAnimation, "animateLabel");

 
 
 
Strings and Int
posted by ChrisNTR
The following example displays an integer's value as a text label:
var currentInt = 5;
exampleLabel.Text = String.Format("Int = {0}", currentInt);

 
 
 
Regular Expressions (RegEx)
posted by ChrisNTR
var emailRegex = @"^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$";
var realEmail = "my@email.com";
var fakeEmail = "notAEmailAddress.com";
var formatString = "{0} is a real e-mail = {1}";
Console.WriteLine ((String.Format(formatString, realEmail, Regex.IsMatch(realEmail, emailRegex))));			
Console.WriteLine ((String.Format(formatString, fakeEmail, Regex.IsMatch(fakeEmail, emailRegex))));

 
 
 
Draggable Items
posted by ChrisNTR
Here's how to create a simple draggable image. 1. Create a new class that inherits from UIImageView.
public class MyDraggableImage : UIImageView
{
	public MyDraggableImage(RectangleF frame) : base(frame)
	{
	}

	public PointF StartLocation { get; set; }
}
2. In the implementation for this new class, add the 3 methods:
public override void TouchesBegan (NSSet touches, UIEvent evt)
{
	var pt = (touches.AnyObject as UITouch).LocationInView(this);
	StartLocation = pt;
	this.Superview.BringSubviewToFront(this);
}
	
public override void TouchesMoved (NSSet touches, UIEvent evt)
{
	// Move relative to the original touch point 
	var pt = (touches.AnyObject as UITouch).LocationInView(this);
	var frame = this.Frame;
	frame.X += pt.X - StartLocation.X;
	frame.Y += pt.Y - StartLocation.Y;
	this.Frame = frame;
}
		
public override void TouchesEnded (NSSet touches, UIEvent evt)
{
	// Move relative to the original touch point 
	var pt = (touches.AnyObject as UITouch).LocationInView(this);
	var frame = this.Frame;
	frame.X += pt.X - StartLocation.X;
	frame.Y += pt.Y - StartLocation.Y;
	this.Frame = frame;
} 
3. Now instantiate the new class as you would any other new image and add it to your view.
var image = UIImage.FromFile("myImage.png");
var draggableRect = new RectangleF(0f, 0f, image.Size.Width, image.Size.Height);
var dragger = new MyDraggableImage(draggableRect);
dragger.Image = image;
dragger.UserInteractionEnabled = true;
view.AddSubview(dragger);

 
 
 
Vibrate and Sound
posted by ChrisNTR
Here is how to make the phone vibrate (Note: Vibration does not work in the Simulator, it only works on the device.)
SystemSound.Vibrate.PlaySystemSound();
Sound will work in the Simulator, however some sound (such as looped) has been reported as not working in Simulator or even altogether depending on the audio format. Note there are specific filetypes that must be used (.caf in this example).
var sound = new SystemSound(new NSUrl("audioFile.caf"));
sound.PlaySystemSound();

 
 
 
Threading
posted by ChrisNTR
1. Create the new thread:
var thread = new Thread(NewThreadMethod as ThreadStart);
thread.Start();
2. Create the method that is called by the new thread:
[Export("NewThreadMethod")]
void NewThreadMethod()
{
	using(var pool = new NSAutoreleasePool())
	{
		// Run code in new thread
	}
}
What if you need to do something to the main thread from inside your new thread (for example, show a loading symbol)? Use InvokeOnMainThread.
InvokeOnMainThread( delegate {
	// Update UI Code (in Main thread) from the new thread.	
});

 
 
 
Reading crash logs
posted by ChrisNTR
If you're in the unfortunate position of having to decipher a crash log, navigate here to give them meaning.
(Taken straight from iphoneexamples.com)

 
 
 
Testing
posted by ChrisNTR
1. In Simulator, click Hardware > Simulate Memory Warning to test. You may need to enable this setting on each new page of your app.
2. Be sure to test your app in Airplane Mode.
(Taken straight from iphoneexamples.com)

 
 
 
Access properties/methods in other classes
posted by ChrisNTR
One way to do this is via the AppDelegate:
var appDelegate = (AppDelegate) UIApplication.SharedApplication.Delegate;
appDelegate.view.BackgroundColor = UIColor.Green;

 
 
 
Random Numbers
posted by ChrisNTR
Random r = new Random();
var randomNumber = r.Next();

 
 
 
Timers
posted by ChrisNTR
This timer will call OneSecondTimer every 1 second.
var timer = NSTimer.CreateRepeatingScheduledTimer(TimeSpan.FromSeconds(1), OneSecondTimer);
What if you need to pass an object to OneSecondTimer? Use the "userInfo" property.

1. First create the Timer
var userInfo = new NSString("MyUserInfo");
var timer = NSTimer.CreateScheduledTimer(1, this, new Selector("OneSecondTimer"), userInfo, true);
2. Then pass the NSTimer object to your method:
[Export("OneSecondTimer")]
void OneSecondTimer(NSTimer timer)
{
	var userInfoString = timer.UserInfo.ToString();	
}
To stop a timer, use "invalidate":
timer.Invalidate();
timer = null;

 
 
 
Application analytics
posted by ChrisNTR
There are a few options for Application analytics on the iPhone. Two that I have seen are PinchMedia and Google Analytics. You can find Monotouch libraries for these here although there may be a issue with running this on the device so use with caution.

 
 
 
Time
posted by ChrisNTR
Calculate the passage of time by using DateTime.UtcNow;
var currentTime = DateTime.UtcNow;
Console.WriteLine ("Date/Time: " + currentTime);

 
 
 
Alerts
posted by ChrisNTR
Show a simple alert with OK button.
using(var alert = new UIAlertView("Title", "Message", null, "OK", null))
{
	alert.Show();	
}

 
 
 
Plist files
posted by ChrisNTR
For most cases, you can just use the default Plist provided for an application. I will expand on this in the future.
var plist = NSUserDefaults.StandardUserDefaults;
var myKey = plist["myKey"];
// Or
var myKey2 = plist.StringForKey("myKey2");
var myBoolKey = plist.BoolForKey("myBoolKey");
var myIntKey = plist.IntForKey("myIntKey");
			
plist.SetString("Save this string", "myStringKey");
// Saves the new "myStringKey" string.
plist.Synchronize();

 
 
 
Info button
posted by ChrisNTR
The default info button can be difficult to touch on the device. This code increases the size.
var f = infoButton.Frame;
var newInfoButtonRectangle = new RectangleF(f.X - 25f, f.Y - 25f, f.Width + 50f, f.Height + 50f);
infoButton.Frame = newInfoButtonRectangle;

 
 
 
Detecting Subviews
posted by ChrisNTR
You can loop through subviews of an existing view. This works especially well if you use the "tag" property on your views.
foreach(var view in this.window.Subviews)
{
	Console.WriteLine ("View" + view.ToString());
	foreach(var subView in this.view.Subviews)
	{
		Console.WriteLine ("SubView: " + subView.ToString());
	}
}