How to change UITextField keyboard type to email in Swift

ぐ巨炮叔叔 提交于 2020-06-09 07:48:04

问题


In objective-c I can just say the following.

[self.promoTextField setKeyboardType:UIKeyboardTypeEmailAddress];

I tried googling it but just get ways to do it in objective-c.


回答1:


Try this :

Swift 3

self.promoTextField.keyboardType = UIKeyboardType.emailAddress

Swift < 3

self.promoTextField.keyboardType = UIKeyboardType.EmailAddress



回答2:


The documentation about UITextInputTraits, a protocol adopted by UITextField, says it's still here:

optional var keyboardType: UIKeyboardType { get set }

And the list of all keyboardTypes is here :

enum UIKeyboardType : Int {
    case Default
    case ASCIICapable
    case NumbersAndPunctuation
    case URL
    case NumberPad
    case PhonePad
    case NamePhonePad
    case EmailAddress
    case DecimalPad
    case Twitter
    case WebSearch
}



回答3:


In Swift 3 you might use:

youremailfieldname.keyboardType = UIKeyboardType.emailAddress

Note the lowercase in emailAddress

Note: also that you can assign the keyboard type in the TextField definition in the storyboard.




回答4:


Try it in Swift 3:

let emailTextField: UITextField = {
    let text = UITextField()
    text.keyboardType = .emailAddress

    return text
}()



回答5:


You should just set the type of entry to TextField you want to change. e.g.

self.yourlTextField.keyboardType = .emailAddress //shows keyboard with e-mail characters

self.yourTextField.keyboardType = .phonePad ////shows phone pad only..just numbers



回答6:


Sometimes give UITextField extension to add one method, you can use like that "textField.chooseKeyboardType(keyboardType:.pad)", perhaps this is not a good way, but useful.

public extension UITextField {

func chooseKeyboardType(_ keyboardType:UIKeyboardType) {
    switch keyboardType {
    case .emailAddress:
        self.keyboardType = .emailAddress
    case .twitter:
        self.keyboardType = .twitter
    case .numberPad:
        self.keyboardType = .numberPad
    case .numbersAndPunctuation:
        self.keyboardType = .numbersAndPunctuation
    case .asciiCapable:
        self.keyboardType = .asciiCapable
    case .URL:
        self.keyboardType = .URL
    case .decimalPad:
        self.keyboardType = .decimalPad
    case .namePhonePad:
        self.keyboardType = .namePhonePad


    default:
        self.keyboardType = .default
    }
}
}


来源:https://stackoverflow.com/questions/26404373/how-to-change-uitextfield-keyboard-type-to-email-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!