Datta Datta - 4 years ago 173
C# Question

How to disable space character in a text field in ios xamarin

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);
};

Answer Source

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;
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download