在UITextField中显示"#"而不是"bullets" "Secure Text Entry"



我需要在密码字段中显示"#">而不是项目符号。但是由于UITextField中没有可用的默认选项。

我尝试在"应该更改字符范围">中编写自定义逻辑但是当用户从两者之间删除或添加任何特定字符时,我无法处理索引。

所以这是我的问题:- 1. 我需要找到任何库吗 2.还有其他默认选项吗? 3. 需要为其编写自定义逻辑?如果是这样,我可以正确处理它">应该更改字符范围">"文本字段DidChange">

  1. 不,您不需要为此逻辑找到任何第三方库
  2. 否,没有默认选项可以满足您的需求
  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
    }
    

斯威夫特 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
}

使用不带安全输入选项的普通文本字段。当用户输入字符时,将其保存到字符串变量中,并在文本字段中将其替换为要显示的字符而不是项目符号。

 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 中。希望对您有所帮助!!

改进了憨豆先生在 swift 5 中的回答。修复复制和粘贴错误。

var passNSString : NSString = ""
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        var hashPassword = String()
        
        passNSString = passNSString.replacingCharacters(in: range, with: string) as NSString
        for _ in 0..<passNSString.length {  hashPassword += "#" }
        textField.text = hashPassword
        print("str", passNSString)
        return false
        
    }

最新更新