我要求在密码字段中显示"#" 而不是bullets。 但是由于在 UITextField 中没有可用的默认选项。
我尝试在"shouldChangeCharactersInRange" 中编写自定义逻辑 但是当用户从中间删除或添加任何特定字符时,我无法处理索引。
所以这是我的问题:- 1.我需要找图书馆吗 2. 还有其他默认选项吗? 3.需要为其编写自定义逻辑吗?如果是这样,我可以在哪里正确处理它 "shouldChangeCharactersInRange" 或 "textFieldDidChange"
最佳答案
- 不,您不需要为此逻辑找到任何第 3 方库
- 否 没有满足您需要的默认选项
是的,你需要为你的需求写一个自定义逻辑,所以就这样......
var passwordText = String() func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if textField == textFieldPassword { var hashPassword = String() let newChar = string.characters.first let offsetToUpdate = passwordText.index(passwordText.startIndex, offsetBy: range.location) if string == "" { passwordText.remove(at: offsetToUpdate) return true } else { passwordText.insert(newChar!, at: offsetToUpdate) } for _ in passwordText.characters { hashPassword += "#" } textField.text = hashPassword return false }
swift 4:-
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == textFieldPassword {
var hashPassword = String()
let newChar = string.first
let offsetToUpdate = passwordText.index(passwordText.startIndex, offsetBy: range.location)
if string == "" {
passwordText.remove(at: offsetToUpdate)
return true
}
else { passwordText.insert(newChar!, at: offsetToUpdate) }
for _ in 0..<passwordText.count { hashPassword += "#" }
textField.text = hashPassword
return false
}
return true
}
关于ios - 在 "#"的 UITextField 中显示 "bullets"而不是 "Secure Text Entry",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43929642/