Created
July 11, 2011 11:18
-
-
Save davidroth/1075682 to your computer and use it in GitHub Desktop.
A simple helper class for monotouch which provides you an easy to use API for showing alerts with buttons. The class will handle the reference tracking and alert queue for you.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Fusonic.Monotouch.Utils | |
{ | |
public class ButtonAction | |
{ | |
public ButtonAction (string title, Action callback) | |
{ | |
Title = title; | |
Callback = callback; | |
} | |
public string Title { get; set; } | |
public Action Callback { get; set;} | |
} | |
public class UIAlertHelper | |
{ | |
private static readonly List<UIAlertView> activeViews = new List<UIAlertView>(); | |
private static readonly List<UIAlertView> queuedViews = new List<UIAlertView>(); | |
public static void ShowAlert(string title, string message, string cancelButtonTitle, params ButtonAction[] actions) | |
{ | |
string[] buttons = (actions != null) ? | |
actions.Select(x => x.Title).ToArray() : null; | |
UIAlertView alertView = new UIAlertView(title, message, null, cancelButtonTitle, buttons); | |
alertView.Clicked += (sender, e) => HandleAlertViewClicked(alertView, e, actions); | |
alertView.Dismissed += HandleAlertViewDismissed; | |
if(activeViews.Count == 0) | |
{ | |
alertView.Show(); | |
activeViews.Add(alertView); | |
} | |
else | |
{ | |
queuedViews.Add(alertView); | |
} | |
} | |
static void HandleAlertViewDismissed (object sender, UIButtonEventArgs e) | |
{ | |
UIAlertView alertView = (UIAlertView)sender; | |
if(activeViews.Contains(alertView)) | |
{ | |
activeViews.Remove(alertView); | |
if(queuedViews.Count > 0) | |
{ | |
UIAlertView first = queuedViews.First(); | |
first.Show(); | |
activeViews.Add(first); | |
queuedViews.Remove(first); | |
} | |
} | |
} | |
static void HandleAlertViewClicked (UIAlertView alertView, UIButtonEventArgs e, ButtonAction[] actions) | |
{ | |
if(actions == null) { | |
return; | |
} | |
string title = alertView.ButtonTitle(e.ButtonIndex); | |
ButtonAction action = actions.SingleOrDefault(x => x.Title == title); | |
if(action != null) | |
{ | |
action.Callback(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment