如何禁用" Space"键盘在Swift键盘?

时间:2014-11-27 13:47:02

标签: ios swift keyboard

我正在创建一个登录系统,我不希望在用户名字段中允许使用空格。我没有检查和验证字段,而是希望防止添加空格。

因此,每次用户按空格键时,都不会发生任何事情。我怎样才能做到这一点? 我见过Instagram就这么做了。

到目前为止,这是我的代码:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var signUp: UIBarButtonItem!
    @IBOutlet weak var navBar: UINavigationBar!
    @IBOutlet weak var UsernameText: UITextField!


    override func viewDidLoad() {
        super.viewDidLoad()

             self.navigationController?.navigationBar.clipsToBounds = true
        UsernameText.attributedPlaceholder = NSAttributedString(string:"TypeYourUsername",
            attributes:[NSForegroundColorAttributeName: UIColor.whiteColor()])

        func textField(UsernameText: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
            if (string == " ") {
                return false
            }
            return true
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillAppear(animated: Bool) {
        UsernameText.becomeFirstResponder()
    }


    override func prefersStatusBarHidden() -> Bool {
        return true
    }
}

9 个答案:

答案 0 :(得分:17)

是的,你可以做到。覆盖UITextField委托方法shouldChangeCharactersInRange。并在该方法中检查空格字符。如果找到则返回false。

注意:不要忘记为textfield设置委托。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if (string == " ") {
        return false
    }
    return true
}

修改:更多代码

class ViewController : UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField : UITextField!

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

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        if (string == " ") {
          return false
        }
        return true
    }
}

此处textField对象是IBOutlet。这意味着文本字段控件位于故事板中并与此变量相关联。

答案 1 :(得分:6)

在Swift 2.0中

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let whitespaceSet = NSCharacterSet.whitespaceCharacterSet()
    let range = string.rangeOfCharacterFromSet(whitespaceSet)
    if let _ = range {
        return false
    }
    else {
        return true
    }
}

答案 2 :(得分:5)

Swift 4.1 / 4.2 Xcode 10.1

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

if string == " " {
    return false
}else{
    return true
}
}

答案 3 :(得分:3)

在Swift 2.1中

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let whitespaceSet = NSCharacterSet.whitespaceCharacterSet()
    if let _ = string.rangeOfCharacterFromSet(whitespaceSet) {
       return false
       }
    return true
}

答案 4 :(得分:2)

Swift 3

class SignUpViewController: UIViewController, UITextFieldDelegate {

lazy var emailTextField: UITextField = {
    let tf = UITextField()
    tf.translatesAutoresizingMaskIntoConstraints = false
    tf.placeholder = "Email address"
    tf.delegate = self
    return tf
}()

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let whitespaceSet = NSCharacterSet.whitespaces

    if let _ = string.rangeOfCharacter(from: whitespaceSet) {
        return false
    }
    else {
        return true
    }
}
}

答案 5 :(得分:2)

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

答案 6 :(得分:0)

Swift 4.1

使用单行代码就很简单,您可以停止空格

对于所有文本字段

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

        textField.text = textField.text?.replacingOccurrences(of: " ", with: "")
        return true
    }

对于单个文本字段

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

    if textField == txtid
    {
        textField.text = textField.text?.replacingOccurrences(of: " ", with: "")
    }
    return true
}

答案 7 :(得分:0)

在这里您可以禁用空格,直到输入您的(第一个字符)文本为止。 (一些改进)

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let whitespaceSet = NSCharacterSet.whitespaces
        let range = string.rangeOfCharacter(from: whitespaceSet)
        if let _ = range {
            let text = textField.text ?? ""
            if text.isBlankByTrimming || text.isEmpty {
                return false
            }else {
               return true
            }
        }
        else {
            return true
        }
    }

在这里您可以使用此扩展程序来修剪空白(即使您正在检查验证时) 使用上面的文本字段代理,您可以禁用空格,但是如果有这样的字符串

 Example : "MyName Surname             "  

因此也可以在保存此数据之前修剪末端空格。

    extension String {
        var isBlankByTrimming: Bool {
            let trimmed = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
            return trimmed.isEmpty
        } 
       func trimWhitespacesAndNewlines() -> String{
              return self.trimmingCharacters(in: 
                                CharacterSet.whitespacesAndNewlines)
        }
     }

使用::

let yourString = "MyName Surname          " 
let finalString = yourString.trimWhitespacesAndNewlines()

答案 8 :(得分:0)

Swift 5

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return string != " "
}

这对我来说是最容易理解的语法。