强制小写 - ios迅速

时间:2015-10-18 08:42:16

标签: ios xcode swift uitextfield

我想在用户输入时强制UITextfield小写。 到目前为止我用这段代码出来了,但似乎并没有降低字符。

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

4 个答案:

答案 0 :(得分:8)

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

textfield.autocapitalizationType = UITextAutocapitalizationType.None

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

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
}

答案 1 :(得分:3)

当事情发生变化时,您可以这样做并小写整个字符串。

textfield.addTarget(self, action: "textViewChanged", forControlEvents: .EditingChanged);


  func textViewChanged(){
        textfield.text = textfield.text?.lowercaseString;
    }

答案 2 :(得分:1)

对于swift 3用户,Abhinav给出的上述代码只是转换为以下

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

    if let _ = string.rangeOfCharacter(from:NSCharacterSet.uppercaseLetters) {

        return false
    }

    return true
}

答案 3 :(得分:1)

如果要将所有输入字符都转换为小写,则应执行以下代码:

快捷键4:

override func viewDidLoad()中添加:

 textfield.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: UIControlEvents.editingChanged)

,然后将此函数添加到您的班级:

@objc func textFieldDidChange(_ textField: UITextField) {
        if let text:String = textfield.text {
            DispatchQueue.main.async {
                self.textfield.text = text.lowercased()
            }
        }

}

有必要在主线程中进行更改。