ShouldChangeTextInRange不被UITextView调用

我用户自定义UITextView,并需要隐藏键盘上返回点击。 我需要赶上'ShouldChangeTextInRange'有什么textview,我不知道为什么,但方法不叫。 这里是我的文字视图的代码:

public class PlaceholderTextView : UITextView { public PlaceholderTextView () { Initialize (); } public PlaceholderTextView (CGRect frame) : base (frame) { Initialize (); } public PlaceholderTextView (IntPtr handle) : base (handle) { Initialize (); } void Initialize () { Text = Placeholder; ShouldBeginEditing = t => { if (Text == Placeholder) Text = string.Empty; return true; }; ShouldEndEditing = t => { if (string.IsNullOrEmpty (Text)) Text = Placeholder; return true; }; } public override bool ShouldChangeTextInRange (UITextRange inRange, string replacementText) { if (Text.Equals ("\n")) { this.EndEditing (true); return false; } else { return true; } } } 

在您的UITextView子类中,添加IUITextViewDelegate并实现ShouldChangeText (selector = textView:shouldChangeTextInRange:replacementText:

 public class MyTextView : UITextView, IUITextViewDelegate { string Placeholder; public MyTextView() { Initialize(); } public MyTextView(Foundation.NSCoder coder) : base(coder) { Initialize(); } public MyTextView(Foundation.NSObjectFlag t) : base(t) { Initialize(); } public MyTextView(IntPtr handle) : base(handle) { Initialize(); } public MyTextView(CoreGraphics.CGRect frame) : base(frame) { Initialize(); } public MyTextView(CoreGraphics.CGRect frame, NSTextContainer textContainer) : base(frame, textContainer) { Initialize(); } void Initialize() { Delegate = this; } [Export("textViewShouldBeginEditing:")] public bool ShouldBeginEditing(UITextView textView) { if (Text == Placeholder) Text = string.Empty; return true; } [Export("textViewShouldEndEditing:")] public bool ShouldEndEditing(UITextView textView) { if (string.IsNullOrEmpty(Text)) Text = Placeholder; return true; } [Export("textView:shouldChangeTextInRange:replacementText:")] public bool ShouldChangeText(UITextView textView, NSRange range, string text) { if (text.Contains("\n")) { this.EndEditing(true); return false; } return true; } } 

注意:不能混用ObjC / Swift样式的委托和C#匿名委托,否则最后会出现错误:

事件注册覆盖现有的代理。 要么只是使用事件或你自己的代表