【问题标题】:How do I prevent one specific character to be entered into a UITextView (in Xamarin)?如何防止将一个特定字符输入到 UITextView(在 Xamarin 中)?
【发布时间】:2015-03-13 00:12:28
【问题描述】:

我需要防止用户在 UITextView 中实现的注释字段中输入插入符号 ("^")。我发现了这个问题:prevent lower case in UITextView,但我不清楚何时/多久调用一次shouldChangeTextInRange 方法。每次击键都会调用它吗?之所以这样命名是因为它会被调用一次以进行粘贴吗?我宁愿去掉有问题的插入符号,而不是阻止整个粘贴操作,这看起来不像那种方法可以做到的。

我们的主应用程序(用 VCL 组件用 C++Builder 编写)可以过滤击键,因此如果按下 ^,它会发出哔哔声并且字符不会添加到文本字段中。我想在这里复制这种行为。

有没有办法在 Xamarin 中理智地做到这一点?我先做 iOS,以后可能会问 Android。

感谢您的帮助!

【问题讨论】:

  • 你应该使用委托方法,textView:shouldChangeTextInRange:replacementText:。每次击键后都会调用它。
  • 谢谢 rdelmar,我就是这么想的。这意味着我需要找到另一种解决方案,以便可以过滤粘贴的文本,而不仅仅是拒绝。

标签: ios xamarin


【解决方案1】:

您是否使用 Xamarin.Forms 来构建您的 UI?如果您打算以 Android 为目标,我强烈建议您这样做。

如果是这种情况,那么您可以使用自定义 Entry 子类轻松做到这一点:

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

用法:

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

输入的^ 将从条目的文本中删除。

【讨论】:

  • 谢谢,乔希!不幸的是,我在 Xamarin.Forms 发布之前完成了这个应用程序的初始开发。我希望在今年晚些时候使用 Forms 重新编写它,但我有更高优先级的项目要先完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-14
  • 1970-01-01
  • 2018-02-22
  • 2015-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多