防止UITextField中的特殊字符

时间:2016-04-26 18:20:10

标签: swift uitextfield special-characters

如何阻止用户在UITextField

中输入特殊字符

5 个答案:

答案 0 :(得分:3)

我使用此代码解决了问题:

let validString = NSCharacterSet(charactersInString: " !@#$%^&*()_+{}[]|\"<>,.~`/:;?-=\\¥'£•¢")

// restrict special char in test field
if (textField == self.txt_firstName || textField == self.txt_lastName)
{
    if let range = string.rangeOfCharacterFromSet(validString)
    {
        print(range)
        return false
    }
    else
    {
    }
}

答案 1 :(得分:0)

Swift 4.2

表情符号和特殊字符

override func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField.isFirstResponder {
            let validString = CharacterSet(charactersIn: " !@#$%^&*()_+{}[]|\"<>,.~`/:;?-=\\¥'£•¢")

            if (textField.textInputMode?.primaryLanguage == "emoji") || textField.textInputMode?.primaryLanguage == nil {
                return false
            }
            if let range = string.rangeOfCharacter(from: validString)
            {
                print(range)
                return false
            }
        }
        return true
    }

答案 2 :(得分:0)

默认答案为CharacterSet的另一个答案

限制所有特殊字符,如果您不想限制任何字符串,这将支持。

extension String {
    var containsValidCharacter: Bool {
        guard self != "" else { return true }
        let noNeedToRestrict = CharacterSet(charactersIn: " _") // NOT RESTRICT "Underscore and Space"
        if noNeedToRestrict.containsUnicodeScalars(of: self.last!) {
            return true
        } else {
            return CharacterSet.alphanumerics.containsUnicodeScalars(of: self.last!)
        }
    }
}
extension CharacterSet {
    func containsUnicodeScalars(of character: Character) -> Bool {
        return character.unicodeScalars.allSatisfy(contains(_:))
    }
}

用法:

extension ViewController: UITextFieldDelegate {

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

答案 3 :(得分:0)

以下示例说明如何允许用户仅使用 RxSwift 键入字母数字字符。

添加 RxSwift pod

pod 'RxSwift', '~> 5'

创建一个字符串扩展以删除集合中的字符

extension String {

    func removeChars(in set: CharacterSet) -> String {
        let filtered = self.unicodeScalars.filter { (scalarElement) -> Bool in
            if (set.contains(scalarElement)) {
                return false
            }

            return true
        }
        
        let trimmed = String(filtered.map({ (scalar) -> Character in
            return Character(scalar)
        }))
        
        return trimmed
    }

}

使用 RxSwift 扩展在文本更改时删除无效字符

import UIKit
import RxSwift


class MyViewController: UIViewController {
    
    private let disposeBag = DisposeBag()


    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUpView()
    }

    private func setUpView() {
        //Do view set up stuff here

        //Use the extension here to listen to text changes and remove chars
        myTextField.rx.text
            .asDriver(onErrorJustReturn: "")
            .drive(onNext: { [weak self] (text: String?) in
                //Here you would change the character set to what you need
                let newText = text?.removeChars(in: CharacterSet.alphanumerics.inverted)
                self?.myTextField.text = newText
            })
            .disposed(by: disposeBag)
    }

}

答案 4 :(得分:-1)

尝试

self.DataTblView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)