本文介绍了强制小写 - ios swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户键入时在 UITextfield 中强制使用小写.到目前为止,我已经使用了这段代码,但似乎并没有降低字符.

I would like to force lowercase in an UITextfield when the user is typing. I came out so far with this code, but seems like it's not lowering characters.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if string.characters.count == 0 {
        return true
    }

    let currentText = textField.text ?? ""
    let prospectiveText = (currentText as NSString).stringByReplacingCharactersInRange(range, withString: string.lowercaseString)

    switch textField {
    // Allow only lower-case vowels in this field,
    // and limit its contents to a maximum of 6 characters.
    case userNameTextField:
        return prospectiveText.characters.count <= 27
    default:
        return true
    }
}

推荐答案

首先,您应该在文本字段上设置以下属性以限制自动大写:

First you should set following property on your textfield to restrict auto capitalisation:

textfield.autocapitalizationType = UITextAutocapitalizationType.None

这就是您可以进一步限制它的方法:

And this is how you can restrict it further:

func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {

    if let _ = string.rangeOfCharacterFromSet(NSCharacterSet.uppercaseLetterCharacterSet()) {
        // Do not allow upper case letters
        return false
    }

    return true
}

SWIFT 4 更新

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if let _ = string.rangeOfCharacter(from: .uppercaseLetters) {
        // Do not allow upper case letters
        return false
    }

    return true
}

这篇关于强制小写 - ios swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 08:44