1

I need to prevent users from entering a caret ("^") into a notes field that is implemented in a UITextView. I found this question: prevent lower case in UITextView, but it's not clear to me when/how often the shouldChangeTextInRange method will be called. Is it called for each keystroke? Is it named this way because it will be called once for a paste? Instead of preventing the entire paste operation, I'd rather strip out the offending carets, which it doesn't look like that method can do.

Our main application (written in C++Builder with VCL components) can filter keystrokes, so that if ^ is pressed, it beeps and the character is not added to the text field. I would like to replicate that behavior here.

Is there any way to do that sanely in Xamarin? I'm doing iOS first, and might be asking about Android later.

Thanks for your help!

Community
  • 1
  • 1
Karen Cate
  • 272
  • 3
  • 15
  • You should use the delegate method, textView:shouldChangeTextInRange:replacementText:. It is called after every keystroke. – rdelmar Mar 13 '15 at 01:40
  • Thanks rdelmar, that's what I thought. That means I need to find another solution so that pasted text can be filtered, instead of just rejected. – Karen Cate Apr 27 '15 at 22:23

1 Answers1

1

Are you using Xamarin.Forms to build your UI? If you're going to be targeting Android, I highly recommend doing so.

If that is the case, then you can easily do this with a custom Entry subclass:

public class FilteredEntry : Entry
{
    private string FilterRegex { get; set; }

    public FilteredEntry (string filterRegex)
    {
        // if we received some regex, apply it
        if (!String.IsNullOrEmpty (filterRegex)) {

            base.TextChanged += EntryTextChanged;

            FilterRegex = filterRegex;
        }
    }

    void EntryTextChanged (object sender, TextChangedEventArgs e)
    {
        string newText = e.NewTextValue;

        (sender as Entry).Text = Regex.Replace (newText, FilterRegex, String.Empty);
    }
}

Usage:

// The root page of your application
MainPage = new ContentPage {
    Content = new StackLayout {
        VerticalOptions = LayoutOptions.Center,
        Children = {
            new FilteredEntry(@"\^")
        }
    }
};

A typed ^ will be stripped out of the Entry's Text.

Josh
  • 12,448
  • 10
  • 74
  • 118
  • Thanks, Josh! Unfortunately, I finished my initial development of this app just before Xamarin.Forms was released. I hope to re-write it using Forms later this year, but I have higher priority projects to complete first. – Karen Cate Apr 27 '15 at 22:22