Reputation: 61
I don't want to allow to enter space in display name field.
For example if the user types the name like this " Name" or " Name" or " Name ", the end result should be "Name" eliminating the spaces.
I tried this approach but the trim doesn't seem to work.
NameText.EditingDidEnd += delegate {
char[] arr = new char[] {' '};
NameText.Text.TrimStart(arr);
ScrollPageForKeyboard(false);
};
Upvotes: 0
Views: 2010
Reputation: 74174
I would suggest preventing the user from actually entering whitespace versus removing it after they all ready have.
Add a ShouldChangeCharacters
handler and check to see if they are entering any characters in the whitespace character set as defined by NSCharacterSet.WhitespaceAndNewlines
NameText.ShouldChangeCharacters += (UITextField textField, NSRange range, string replacementString) =>
{
foreach (var aChar in replacementString)
{
if (NSCharacterSet.WhitespaceAndNewlines.Contains(aChar))
return false;
}
return true;
};
Upvotes: 1
Reputation: 1484
Using the String.Trim()
method should work nicely here:
NameText.EditingDidEnd += delegate
{
var trimmedName = DisplayNameText.Text.Trim();
ScrollPageForKeyboard(false);
};
You could also use a Regex
to replace all white space completely:
NameText.EditingDidEnd += delegate
{
var trimmedName = Regex.Replace(DisplayNameText.Text, @"\s+", "");
ScrollPageForKeyboard(false);
};
Upvotes: 1
Reputation: 3001
If you just want to remove leading and trailing spaces (" Name" or "Name "), then use:
DisplayNameText.Text = DisplayNameText.Text.Trim()
as recommended in the comments. If you want to remove all spaces ("John Smith" = "JohnSmith"), then use
DisplayNameText.Text = DisplayNameText.Text.Replace(" ", "")
to remove all the spaces.
Upvotes: 2