我需要阻止用户在 UITextView
中实现的备注字段中输入插入符 ("^")。我发现了这个问题:prevent lower case in UITextView ,但我不清楚何时/多久调用一次 shouldChangeTextInRange
方法。每次击键都会调用它吗?这么命名是不是因为贴一次就会调用一次?与其阻止整个粘贴操作,我宁愿删除有问题的插入符,这看起来不像该方法可以做到的。
我们的主要应用程序(使用 VCL 组件用 C++Builder 编写)可以过滤击键,因此如果按下 ^,它会发出蜂鸣声并且不会将字符添加到文本字段中。我想在这里复制这种行为。
有没有办法在 Xamarin 中理智地做到这一点?我先做 iOS,以后可能会问 Android。
感谢您的帮助!
最佳答案
您是否使用 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(@"\^")
}
}
};
键入的 ^
将从条目的文本中删除。
关于ios - 如何防止将一个特定字符输入到 UITextView(在 Xamarin 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29022667/