UITextField.MaxLength (or something like it)

So, I need to enforce: Numbers only, and a maximum length (Zip code, whee!) of a UITextField on my iPhone app.

Here’s what I came up with (later, I shall implement some sort of RegEx style of doing this)

               bool CheckText(UITextField fld, NSRange rng, string newChar, int maxLength, bool numbersOnly)
		{
			const string numbers = "0123456789";
			if (fld.Text.Length >= maxLength && rng.Length == 0) {
					return false;
				} else {
					if (!numbersOnly)
					return true;
					if (numbers.IndexOf(newChar) >=0)
					return true;
						return false;
				}
		}

and then to attach it to a text field:

               ZipInput.ShouldChangeCharacters = (fld, rng, str) => CheckText(fld,rng,str,5,true);

Easy as pie.

Advertisements

2 thoughts on “UITextField.MaxLength (or something like it)

  1. Hipolyto says:

    this is great!

    thanks

  2. Russell Jackson says:

    Bingo, just what I needed. Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: