gpt4 book ai didi

ios - 不为 UITextView 调用 ShouldChangeTextInRange

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:54:26 25 4
gpt4 key购买 nike

我使用自定义 UITextView,需要在返回点击时隐藏键盘。我需要捕获'ShouldChangeTextInRange'什么有textview,我不知道为什么但是 方法未被调用。这是我的 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(选择器 = 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 风格的委托(delegate)和 C# 匿名委托(delegate),否则你会得到错误:

Event registration is overwriting existing delegate. Either just use events or your own delegate

关于ios - 不为 UITextView 调用 ShouldChangeTextInRange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44112187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com