xcode UITextfield 键盘只有字母,没有数字,没有大写字母,没有空格键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31480558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 07:30:22  来源:igfitidea点击:

UITextfield keyboard with only alphabet, no numbers, no caps, no spacebar?

iosxcodeswift

提问by gooberboobbutt

I want the keyboard for the UITextfield to only have a-z, no numbers, no special characters (!@$!@$@!#), and no caps. Basicly I am going for a keyboard with only the alphabet.

我希望 UITextfield 的键盘只有 az、没有数字、没有特殊字符 (!@$!@$@!#) 和大写字母。基本上我想要一个只有字母的键盘。

I was able to disable the space already. Anyone know how to disable numbers, special characters, and caps? A solution for any of these would be great.

我已经能够禁用该空间。有人知道如何禁用数字、特殊字符和大写字母吗?任何这些的解决方案都会很棒。

Is the best solution to do the below for all the characters but I dont want?

对所有角色执行以下操作的最佳解决方案是但我不想要吗?

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

    if (string == " ") {
        return false
    }

    if (string == "1") {
        return false
    }

    return true
}

回答by Lennet

An easiet way would be:

一个简单的方法是:

if let range = string.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet())
    return true
}
else {
    return false
}

回答by Santiago Carmona González

Swift 3 solution

斯威夫特 3 解决方案

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

     let characterSet = CharacterSet.letters

     if string.rangeOfCharacter(from: characterSet.inverted) != nil {
         return false      
     }
     return true
}

回答by iAj

Update for those who wants to Allow Space, Caps & Backspace Only

为那些只想允许空格、大写和退格的人更新

Swift 4.x, Swift 5.x & up

Swift 4.x、Swift 5.x 及更高版本

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

    if range.location == 0 && string == " " { // prevent space on first character
        return false
    }

    if textField.text?.last == " " && string == " " { // allowed only single space
        return false
    }

    if string == " " { return true } // now allowing space between name

    if string.rangeOfCharacter(from: CharacterSet.letters.inverted) != nil {
        return false
    }

    return true
}

回答by AtulParmar

Swift 4.2 Code Allow only alphabets with allowing backspace if the user wants to remove wrong character

Swift 4.2 代码如果用户想要删除错误的字符,则只允许字母并允许退格

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if string.rangeOfCharacter(from: .letters) != nil || string == ""{
        return true
    }else {
        return false
    }
}

回答by Devil Decoder

all the answers is working when user is not copy and paste in textfield for copy and paste to work use blow code

当用户未在文本字段中复制和粘贴以进行复制和粘贴以使用打击代码时,所有答案都有效

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

    let text = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    let Regex = "[a-z A-Z ]+"
    let predicate = NSPredicate.init(format: "SELF MATCHES %@", Regex)
    if predicate.evaluate(with: text) || string == ""
    {
        return true
    }
    else
    {
        return false
    }

}

回答by Ramprasath Selvam

class ViewController: UIViewController,UITextFieldDelegate {  

     @IBOutlet var phoneTextField:UITextField!

    override func viewDidLoad() {
            super.viewDidLoad() 
    self.phoneTextField.delegate = self
    }

     func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
           {
                let textString = (textField.text! as NSString).replacingCharacters(in: range, with: string)

                if textField == self.phoneTextField  && string.characters.count > 0 {
                    let LettersOnly = NSCharacterSet.Letters
                    let strValid = LettersOnly.contains(UnicodeScalar.init(string)!)
                    return strValid && textString.characters.count <= 10
                }
                return true
            }
    }

Try this code
In above code is only allow 10 char in text field

试试这个代码
在上面的代码中只允许文本字段中的 10 个字符

回答by Chandan Taneja

if isValidInput(Input: yourtextfieldOutletName.text!) == false {
    let alert = UIAlertController(title: "", message;"Name field accepts only alphabatics", preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))

    self.present(alert, animated: true, completion: nil)
}

func isValidInput(Input:String) -> Bool {
    let myCharSet=CharacterSet(charactersIn:"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
    let output: String = Input.trimmingCharacters(in: myCharSet.inverted)
    let isValid: Bool = (Input == output)
    print("\(isValid)")

    return isValid
}

回答by Dasoga

Swift 3 with spaces

带空格的 Swift 3

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if string == " " { return true }
    if let _ = string.rangeOfCharacter(from: CharacterSet.letters){
        return true
    }
    return false
}