Saturday, May 29, 2010

MonoTouch.Dialog: Improved List Documents!

After completing my last example on listing Documents using MonoTouch, Miguel de Icaza pointed out that MonoTouch.Dialog could make it easier. He was right and below are the results.

Two ways to start off, you can add an "IPhone Window-based Project" and then add a "UINavigationController" to the "MainWindow.xib", or do the route I took and create a "iPhone Navigation based Project" and just delete the extra "RootViewController.xib" we won't be needing.



If you haven't already, download MonoTouch.Dialog (use the "Download Source" link at the top) and then add a reference to it in your project and also be sure to add a "using MonoTouch.Dialog" at the top of "Main.cs"

Below is all the code I need to place in Main.cs to do exactly what my last blog post did which used a TON of extra auto generated code. The code I added starts under the "EDITED" comment.

public class Application
 {
  static void Main (string[] args)
  {
   UIApplication.Main (args);
  }
 }

 // The name AppDelegate is referenced in the MainWindow.xib file.
 public partial class AppDelegate : UIApplicationDelegate
 {
  // This method is invoked when the application has loaded its UI and its ready to run
  public override bool FinishedLaunching (UIApplication app, NSDictionary options)
  {
   
   window.AddSubview (navigationController.View);

   
   //EDITED: this is it!!! Takes care of generating the whole Table View!
   var menu = new RootElement ("Documents"){
    new Section("") {
     from ff in System.IO.Directory.GetFiles(Environment.GetFolderPath (Environment.SpecialFolder.Personal)).ToList()
      select (Element) new StringElement (new System.IO.FileInfo(ff).Name)
    }  
   };
   var dv = new DialogViewController (menu) {
    Autorotate = true
   };
   navigationController.PushViewController (dv, true);    
   dv.Style = UITableViewStyle.Plain;
   
   
   window.MakeKeyAndVisible ();
   
   return true;
  }

  // This method is required in iPhoneOS 3.0
  public override void OnActivated (UIApplication application)
  {
  }
  
 }

You'll need to read my last blog post if you need to add some files to the "Documents" directory (there aren't any by default).

Here are the results or those 12 lines of code (yes, the last sample only had 5 lines added but these extra 7 lines eliminated LOTS of auto generated code and is much simpler):



Amazing! Miguel de Icaza and the Mono/MonoTouch crew didn't stop at the awesome achievement of bringing C# and the .NET Framework to IPhone development; with MonoTouch.Dialog they've outright made Apple and their ancient Object-C language embarrassing. If you can't see the ROI on the $400 a MonoTouch license costs, then your time isn't worth money.

Be sure to visit the MonoTouch.Dialog page on Github and Miguel's blog post on it for more amazingness!