ios 如何在Swift中使用“and '单引号和双引号过滤?

cl25kdpy  于 2023-08-08  发布在  iOS
关注(0)|答案(1)|浏览(129)

我想做一个函数,特殊字符应该被过滤掉。就像如果用户在文本区域中输入任何东西,如果他/她输入特殊字符,那么它将抛出并弹出警报。现在它几乎适用于所有字符,除了单引号和双引号,我想包括[“和' ]。谁能帮我一下。非常感谢!!!

func textViewDidChange(_ textView: UITextView) {
        guard var textViewText = textView.text else {
            return
        }
        var specialCharacterSet = CharacterSet(charactersIn: "₹!@#$%^&*()_+{}[]|<>?;=-")
        specialCharacterSet.insert(charactersIn: "'")
        

        if let range = textViewText.rangeOfCharacter(from: specialCharacterSet) {
            textViewText = textViewText.replacingCharacters(in: range, with: "")
            textView.text = textViewText

            let alertController = UIAlertController(title: "Error", message: "Special characters are not allowed!", preferredStyle: .alert)
            alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            present(alertController, animated: true, completion: nil)
        }
    }

字符串

jmp7cifd

jmp7cifd1#

使用这个方法,我也有分享截图供参考(调试)

func setText()
{
    var textViewText = self.txtview?.text ?? ""
    let specialCharacterSet = CharacterSet(charactersIn: "₹!@#$%^&*()_+{}[]|<>?;=-'\"")
    
    if let range = textViewText.rangeOfCharacter(from: specialCharacterSet) {
        textViewText = textViewText.replacingCharacters(in: range, with: "")
        self.txtview?.text = textViewText
        
        let alertController = UIAlertController(title: "Error", message: "Special characters are not allowed!", preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        present(alertController, animated: true, completion: nil)
    }
}

字符串


的数据




相关问题