我要求为密码字段显示“#”而不是项目符号。 但由于UITextField中没有可用的默认选项。
我试图在“shouldChangeCharactersInRange”中编写自定义逻辑 但是当用户从中间删除或添加任何特定字符时,我无法处理索引。
所以这是我的问题: - 1.我需要找到任何图书馆吗? 2.还有其他默认选项吗? 3.需要为它编写自定义逻辑吗?如果是这样我可以正确处理“shouldChangeCharactersInRange”或“textFieldDidChange”
答案 0 :(得分: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
}
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
}
答案 1 :(得分:0)
使用没有安全输入选项的普通文本字段。当用户输入一个字符时,将其保存到字符串变量中,并在文本字段中将其替换为您想要呈现的字符而不是项目符号。
class ViewController: UIViewController,UITextFieldDelegate {
let textField = UITextField(frame :CGRect(x:16,y:50,width:200,height: 40))
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
self.view.addSubview(textField)
textField.becomeFirstResponder()
}
var password: String = ""
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{
password = password+string
textField.text = textField.text!+"#"//Character you want
print("\(password)")
return false
}
}
这是在Swift 2.希望它能帮助!!