如何在 UIAlert 显示时显示键盘 UIAlert 与自定义 UITextLabel 视图

How To Show Keyboard When UIAlert Present Which The UIAlert With Custom UITextLabel View

UIAlertController 与自定义视图和 UITextField 一起出现时如何显示键盘?我的意思是我想要键盘自动显示而无需用户在警报视图中触摸 UITextField

我的代码如下所示以发出警报。

func callAlertConfirmation() {
    let vc = UIViewController()
    vc.preferredContentSize = CGSize(width: 250, height: 70)

    let textBookmark = UITextField(frame: CGRect(x: 10, y: 0, width: 230, height: 40))
    textBookmark.placeholder = "Typing folder name"
    textBookmark.font = UIFont.systemFont(ofSize: 15)
    textBookmark.textColor = UIColor.black
    textBookmark.borderStyle = UITextField.BorderStyle.roundedRect
    textBookmark.autocorrectionType = UITextAutocorrectionType.no
    textBookmark.keyboardType = UIKeyboardType.alphabet
    textBookmark.returnKeyType = UIReturnKeyType.done
    textBookmark.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
    textBookmark.textAlignment = NSTextAlignment.left
    textBookmark.clearButtonMode = .whileEditing
    vc.view.addSubview(textBookmark)

    let alert = UIAlertController(title: "Create New Folder", message: nil, preferredStyle: .alert)
    alert.setValue(vc, forKey: "contentViewController")

    let actOKButton = UIAlertAction(title: "OK", style: .default) { (_) -> Void in
        // action When User Okay
    }
    alert.addAction(actOKButton)
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
    alert.preferredAction = actOKButton
    present(alert, animated: true)
}

当我打电话给

callAlertConfirmation

我得到的结果如下图所示:

但是我想在调用的时候像下面这样的图片

callAlertConfirmation

但是当我使用

alert.addTextField

当出现警报时,我会自动显示键盘。

提前致谢。

我可能错了,但每当我想让 UITextView 或 UITextField 立即显示键盘时,我都会这样做:

textBookmark.becomeFirstResponder()

什么

正如@C4747N 所说,您需要调用

.becomeFirstResponder()

您想在显示警报时调用此方法:

present(alert, animated: true) {
    textBookmark.becomeFirstResponder()
}

你想要的方式 "read" 这就像:

Present the alert and once you're done execute the completion body (make the alert's textField first responder)