iOS 在选择特定元素时保持键盘打开

iOS keep keyboard open when tab a specific element

我有一个 UITextView 和一个按钮。 我需要当用户点击按钮时键盘保持打开状态。

我尝试使用 ShouldEndEditing 函数来 return False,但是用户再也无法关闭键盘了。

有什么想法吗?

我正在使用 Xamrin 表单。

在 Objective-C 中,您将在视图控制器中设置一个“完成编辑”事件,这将立即重新打开键盘。没有视觉上的变化。

-(IBAction) textFieldDoneEditing : (id) sender{
    [sender resignFirstResponder];
    [sender becomeFirstResponder];
}

Xamarin/C# 等价物..超出我的想象。

txtMyTextBox.Ended += (sender, e) =>
{
    txtMyTextBox.ResignFirstResponder();
    txtMyTextBox.BecomeFirstResponder();
};

啊,有趣的问题,您已经知道 UITextFieldDelegate 中的 属性 "ShouldEndEditing",那么您为什么不尝试为您的 UITextField 实现自定义委托?

我给你写了一个例子,我用UISwitch来模拟隐藏键盘的情况,在你的ViewController中,使用下面的代码:

public override void ViewDidLoad ()
        {
            MYTextFieldDelegate myDel = new MYTextFieldDelegate ();

            UITextField textTF = new UITextField ();
            textTF.Frame = new CoreGraphics.CGRect (50, 50, 200, 40);
            textTF.BackgroundColor = UIColor.Red;
            textTF.Delegate = myDel;
            this.Add (textTF);

            UIButton btnTest = new UIButton (UIButtonType.System);
            btnTest.SetTitle ("Test", UIControlState.Normal);
            btnTest.Frame = new CoreGraphics.CGRect (50, 100, 200, 40);
            btnTest.TouchUpInside += delegate {
                this.View.EndEditing (true);
            };
            this.Add (btnTest);

            UISwitch keyboardSwitch = new UISwitch ();
            keyboardSwitch.Frame = new CoreGraphics.CGRect (50, 150, 200, 40);
            keyboardSwitch.ValueChanged += (sender, e) => {
                bool flag = (sender as UISwitch).On;
                myDel.FlagForDisplayKeyboard = flag;
            };
            this.Add (keyboardSwitch);
        }

这是MYTextFieldDelegate.cs:

class MYTextFieldDelegate : UITextFieldDelegate
    {
        public bool FlagForDisplayKeyboard { get; set; }

        public override bool ShouldEndEditing (UITextField textField)
        {
            return FlagForDisplayKeyboard;
        }

        public MYTextFieldDelegate ()
        {
            FlagForDisplayKeyboard = false;
        }
    } 

希望对您有所帮助。