Loren Ramly
Loren Ramly

Reputation: 1111

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

How to show keyboard when UIAlertController is present with Custom View and UITextField? I mean I want to keyboard automatically show without user touch the UITextField in alert view.

My code like below to make a Alert.

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)
}

And when I call

callAlertConfirmation

I get the result like this picture: enter image description here

But I want to picture like below when I call

callAlertConfirmation

enter image description here

But when I use

alert.addTextField

I get keyboard automatically show when alert present.

Thanks in advance.

Upvotes: 0

Views: 448

Answers (2)

mrcfal
mrcfal

Reputation: 454

What

As @C4747N already said, you need to call

.becomeFirstResponder()

When

You want to call this method as you present the alert:

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

The way you want to "read" this is like:

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

Upvotes: 2

Celeste
Celeste

Reputation: 1577

I may be wrong but whenever I want a UITextView or UITextField to show a keyboard immediately i do:

textBookmark.becomeFirstResponder()

Upvotes: 2

Related Questions