【问题标题】:Show "#" instead of "bullets" in UITextField for "Secure Text Entry"在 UITextField 中为“安全文本输入”显示“#”而不是“项目符号”
【发布时间】:2017-05-12 05:04:08
【问题描述】:

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

我尝试在 "shouldChangeCharactersInRange" 中编写自定义逻辑 但是当用户从中间删除或添加任何特定字符时,我无法处理索引。

所以这是我的问题:- 1. 我需要找任何图书馆吗 2. 还有其他默认选项可用吗? 3. 需要为它编写自定义逻辑吗?如果是这样,我可以正确处理它 "shouldChangeCharactersInRange""textFieldDidChange"

【问题讨论】:

标签: ios swift uitextfield


【解决方案1】:
  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
}

【讨论】:

【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    相关资源
    最近更新 更多