我试图使文本框仅接受字母数字输入,但是如何在已经创建的函数中执行此操作而不必创建另一个函数或协议呢?我快要学习4周,我不确定如何使用CharacterSet或Range,但是我只需要输入AZ和0-9,但是输入的内容必须能够按顺序进行,所以如果我将其移动2且我在z上,它将给我1,或者如果我在a上并且我将-1移至9,则我必须使用已经存在的协议2个函数,加密和解密并接受2个参数,一个用于输入的字符串,另一个用于int转换的int字符串,但这也需要一个字符串,我将其转换为int以使用。我只是迷失了如何限制函数的输入以及如何在给定int的情况下遍历索引。
protocol CipherProtocol {
func encrypt (plaintext: String, secret: String) -> String
func decrypt (output: String, secret: String) -> String
}
struct AlphanumericCesarCipher: CipherProtocol {
func encrypt(plaintext: String, secret: String) ->
String {
guard let secret = UInt32(secret) else {
return "error"
}
var encoded = ""
for character in plaintext {
if let alpha = ["A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
"0","1","2","3","4","5","6","7","8","9"] {
}
guard let firstUnicodeScalar = character.alpha.first else {
return "error"
}
let unicode = firstUnicodeScalar.value
let shiftedUnicode = unicode + secret
let shiftedCharacter = String(UnicodeScalar(UInt8(shiftedUnicode))) //what does this line mean
encoded += shiftedCharacter
}
return encoded
}
func decrypt(output: String, secret: String) -> String {
return ""
}
}
答案 0 :(得分:0)
我认为您需要使用“正则表达式”。在这种情况下,您的文本输入将仅接受字母数字或您指定的任何字符集。
在视图控制器中尝试此代码,以仅允许输入a-z,A-Z,0-9字符。然后,您可以使用逻辑来转移或执行所需的其他任务。
override func viewDidLoad() {
super.viewDidLoad()
txt_input.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
do {
let text = (textField.text! as NSString).replacingCharacters(in: range, with: string)
let regex = try NSRegularExpression(pattern: "^([a-zA-Z0-9])$", options: [])
if regex.firstMatch(in: text, options: [], range: NSMakeRange(0, text.count)) != nil {
return true
}
}
catch {
print("ERROR")
}
return false
}