xcode Swift 4 - 如何使用按钮启用/禁用键盘

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47335151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 10:26:48  来源:igfitidea点击:

Swift 4 - How to enable / disable keyboard by using buttons

iosswiftxcodeibaction

提问by Danyl

My tricky problem is :

我棘手的问题是:

I've 2 buttons with 2 UITextView. Like you know, when I push an UITextView, keyboard appear. Well, this is not what I want.

我有 2 个带有 2 个 UITextView 的按钮。如您所知,当我推送 UITextView 时,会出现键盘。嗯,这不是我想要的。

I want to enable / disable the display's keyboard according a specific @IBAction taped.

我想根据录制的特定 @IBAction 启用/禁用显示器的键盘。

The scenario is the following: - First button (Keyboard icon) allow the user to display the keyboard to type something in one of the UITextView, with a FirstResponder init on the top one.

场景如下: - 第一个按钮(键盘图标)允许用户显示键盘以在其中一个 UITextView 中键入内容,在顶部有一个 FirstResponder init。

  • Second button (REC icon) allow the user to speak and display in pre-selected TextView but without displaying keyboard.
  • 第二个按钮(REC 图标)允许用户在预先选择的 TextView 中说话和显示,但不显示键盘

I already known that there is :

我已经知道有:

isUserInteractionEnabled

isUserInteractionEnabled

and

textViewDidBeginEditing

textViewDidBeginEditing

But it doesn't really fit well and/or fix my issue.

但它不太适合和/或解决我的问题。

Here a screen to be more explicit (don't give a mind about the third green validate button, it's just for the .POST feature) :

这里有一个更明确的屏幕(不要介意第三个绿色验证按钮,它仅用于 .POST 功能):

enter image description here

在此处输入图片说明

Thanks for any help!

谢谢你的帮助!

回答by Sandeep Bhandari

If I understand your problem correctly, You don't want the keyboard to appear when user taps on the textField but rather should come up only when user taps on Keyboard button and should dismiss on tapping other button.

如果我正确理解您的问题,您不希望在用户点击 textField 时出现键盘,而应该仅在用户点击键盘按钮时出现,并在点击其他按钮时关闭。

All the posted answers mostly focus only on second part of showing keyboard and dismissing them on tapping button. Whats more tricky is preventing keyboard from appearing in when user taps on textField :)

所有发布的答案大多只关注显示键盘的第二部分,并在点击按钮时关闭它们。更棘手的是防止键盘在用户点击 textField 时出现:)

Possible solutions you can try and their cons:

您可以尝试的可能解决方案及其缺点:

Solution 1:

解决方案1:

Try setting textfield isEnabled = falsesure this will prevent keyboard from appearing when user taps on textField but guess what Keyboard will not appear even on calling textfield.becomeFirstResponder()ahhh trouble :)

尝试设置文本字段,isEnabled = false确保这将防止在用户点击文本字段时出现键盘,但猜猜即使在调用textfield.becomeFirstResponder()ahhh 麻烦时键盘也不会出现:)

Solution 2:

解决方案2:

implementing textFieldShouldBeginEditingof UITextField delegate and returing true or false based on whether used tapped on button or textField itself.

实现textFieldShouldBeginEditingUITextField 委托并根据是否使用点击按钮或 textField 本身返回 true 或 false。

Sure it works but you will need to figure out way to tell textFieldShouldBeginEditingwhy was it triggered because of button or because of touch on textField again complications.

当然它可以工作,但您需要找出方法来说明textFieldShouldBeginEditing为什么它是由于按钮或因为再次触摸 textField 而触发的。

My Solution:

我的解决方案:

Use 2 textFields. One disable user interaction forever and use another textField which will never appear to user but will take care of showing keyboard when required.

使用 2 个文本字段。一个永远禁用用户交互并使用另一个永远不会出现在用户面前但会在需要时显示键盘的文本字段。

Enough talk lets code :)

足够的谈话让代码:)

Step 1:

第1步:

Lets say your textField which appears on screen is called textField

假设您出现在屏幕上的 textField 被称为 textField

textfield.isEnabled = false

This will ensure whatever you do keyboard will not appear for this keyboard.

这将确保无论您做什么键盘都不会出现在此键盘上。

Step 2:

第2步:

Create a temp textField of frame zero (which user can never tap :P )

创建零帧的临时文本字段(用户永远无法点击 :P )

    tempTextField = UITextField(frame: CGRect.zero)
    tempTextField.delegate = self
    self.view.addSubview(tempTextField)

Step 3:

第 3 步:

Now when user taps on show keyboard button, make your temp textField first responder

现在,当用户点击显示键盘按钮时,让您的临时文本字段成为第一响应者

tempTextField.becomeFirstResponder()

and when user taps on other button resignFirstResponderfor tempTextField.

当用户点击resignFirstRespondertempTextField 的其他按钮时。

tempTextField.resignFirstResponder()

Step 4:

第四步:

But wait when user types nothing appears on my textField. Wait simply implement

但是当我的 textField 上没有显示任何内容时,请等待。等简单执行

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == tempTextField {
        self.textfield.text = (self.textfield.text ?? "") + string
    }
    return true
}

EDIT:

编辑:

You don't really need two textFields, you can achieve the same with a UILabeland UITextFieldas well. I chose UITextField as I am not sure what are other requirements of yours!

您实际上并不需要两个 textField,您也可以使用UILabeland实现相同的UITextField效果。我选择 UITextField 是因为我不确定您的其他要求是什么!

Problem fixed. Hope it helps :)

问题已解决。希望能帮助到你 :)

回答by Mohammad Kamran Usmani

Just copy and paste simple code for you accessory button embedded with keypad

只需复制并粘贴简单的代码,即可为您嵌入键盘的附件按钮

 func addKeyboardToolbar()  {
    let ViewForDoneButtonOnKeyboard = UIToolbar()
    ViewForDoneButtonOnKeyboard.sizeToFit()
    let button = UIButton.init(type: .custom)
    button.setImage(UIImage.init(named: "login-logo"), for: UIControlState.normal)
    button.addTarget(self, action:#selector(doneBtnfromKeyboardClicked), for:.touchUpInside)
    button.frame = CGRect.init(x: 0, y: 0, width:UIScreen.main.bounds.width, height: 30) //CGRectMake(0, 0, 30, 30)
    let barButton = UIBarButtonItem.init(customView: button)
    ViewForDoneButtonOnKeyboard.items = [barButton]
    postTextView.inputAccessoryView = ViewForDoneButtonOnKeyboard
}


@IBAction func doneBtnfromKeyboardClicked (sender: Any) {
        self.contentView.endEditing(true)
    }

回答by John D

function to dismiss KeyBoard when button is clicked:

单击按钮时关闭键盘的功能:

@IBAction func hideKeyboard() {
     textView.resignFirstResponder()
 }

function to get keyboard to show up:

使键盘显示的函数:

 @IBAction func showKeyboard() {
     textView.becomeFirstResponder()
 }

回答by JP Aquino

Something like this should work:

这样的事情应该工作:

class MyViewController: UIViewController, UITextViewDelegate {

    @IBOutlet var yourTextView: UITextView

        override func viewDidLoad() {
            super.viewDidLoad()

            yourTextView.delegate = self
        }

        @IBAction func showKeyboard(_ sender: UIButton) {
        self.yourTextView.becomeFirstResponder()

    }

      @IBAction func hideKeyboard(_ sender: UIButton) {
        self.yourTextView.resignFirstResponder()

    }

    }

回答by Kerberos

You say

你说

But it's not really working in my case.

但这在我的情况下并没有真正起作用。

Why?

为什么?

You can disable the textfields interaction with (swift 3):

您可以禁用与 (swift 3) 的文本字段交互:

textField.isUserInteractionEnabled = false

Next, when you click on the keyboard button you can reenable the interaction so when the user click on one of the textfield the keyboard opens.

接下来,当您单击键盘按钮时,您可以重新启用交互,因此当用户单击文本字段之一时,键盘会打开。

On the keyboard dismiss (you can see the UIKeyboardWillHideNotificationcallback notification) you can set the interaction to false.

在键盘关闭(您可以看到UIKeyboardWillHideNotification回调通知)上,您可以将交互设置为 false。