c# - 如何限制 MonoTouch 中的 UITextView 字符限制?

标签 c# xamarin.ios uitextview xamarin

<分区>

我希望用户在 UITextView 中最多只能输入一些数字字符。这也需要与复制粘贴一起使用。我找到了 this solution但它是 Objective C,它有一个缺点,即在达到限制后重置光标位置。

我想要的是一个继承自UITextView、公开MaxCharacters 属性并在其中完成所有工作的类。

最佳答案

此代码基于manicaesar's answer但在达到限制后不会重置插入符位置。

[Register ("LimitedTextView")]
public class LimitedTextView : UITextView
{
    public int MaxCharacters { get; set; }

    void Initialize ()
    {
        MaxCharacters = 140;
        ShouldChangeText = ShouldLimit;
    }

    static bool ShouldLimit (UITextView view, NSRange range, string text)
    {
        var textView = (LimitedTextView)view;
        var limit = textView.MaxCharacters;

        int newLength = (view.Text.Length - range.Length) + text.Length;
        if (newLength <= limit)
            return true;

        // This will clip pasted text to include as many characters as possible
        // See https://stackoverflow.com/a/5897912/458193

        var emptySpace = Math.Max (0, limit - (view.Text.Length - range.Length));
        var beforeCaret = view.Text.Substring (0, range.Location) + text.Substring (0, emptySpace);
        var afterCaret = view.Text.Substring (range.Location + range.Length);

        view.Text = beforeCaret + afterCaret;
        view.SelectedRange = new NSRange (beforeCaret.Length, 0);

        return false;
    }

    public LimitedTextView (IntPtr handle) : base (handle) { Initialize (); }
    public LimitedTextView (RectangleF frame) : base (frame) { Initialize (); }
}

关于c# - 如何限制 MonoTouch 中的 UITextView 字符限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14063465/

相关文章:

c# - 类型转换问题

c# - SetupDiEnumDriverInfo 始终返回错误 259(没有更多可用数据)

c# - 将多维数组转换为字符串并返回

c# - 如何在 Monotouch 中创建多级表?

iphone - iOS4:无法以编程方式滚动到 UITextView 的底部

ios - 在 UITextView.attributedText 中插入 unicode 的正确方法

c# - 在 Func/lambda 表达式中重用方法调用

ios - 单点触控 : How to add a two finger gesture recognizer to UIPageViewController?

ios - Card.io 导致非公共(public) API 使用

ios - 在 UITextView Objective-C 中的文本末尾添加更多按钮?