既然你明确要求Swift,我已经翻译了链接问题中的顶部asnwer.
原文链接:https://www.f2er.com/swift/320136.htmllet notAllowedCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."; func textField( textField: UITextField,shouldChangeCharactersInRange range: NSRange,replacementString string: String) -> Bool { let set = NSCharacterSet(charactersInString: notAllowedCharacters); let inverted = set.invertedSet; let filtered = string .componentsSeparatedByCharactersInSet(inverted) .joinWithSeparator(""); return filtered != string; }