ios - 强制小写 - ios swift

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

最佳答案

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

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
}

关于ios - 强制小写 - ios swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33195946/

相关文章:

ios - 如何在 GLKit 中保存变换矩阵?

ios - 音频输出 callkit ActionSheet - 可以从代码开始吗?

ios - 无法在模拟器 "The operation couldn’ 上运行应用程序无法完成。 (LaunchServicesError 错误 0。)”

ios - UITableview reloadRows 在 Swift 3 中无法正常工作

ios - 自定义 UIView addTarget 或 RxCocoa 订阅中的 UIButton 不起作用

ios - Swift Google Map Marker Tap 事件对我不起作用

ios - 将 SecKey 导出为 pkcs8 格式

ios - 如何截断 UITableView Cell TextLabel 中的文本,使其不隐藏 DetailTextLabel?

objective-c - 在方法名称中使用关键字的危险

ios - 新创建的Apple开发者帐户未显示应用