美文网首页
UITextField 密码明文密文切换光标以及清空问题解决方案

UITextField 密码明文密文切换光标以及清空问题解决方案

作者: wenju | 来源:发表于2021-11-17 10:35 被阅读0次

    不的不说某度找了半天解决都不行,最后还是在google上关键字查到的,该方案来自stackoverflow,放到国内平台来吧,免得查不到,已使用,很方便好用,感觉好用的朋友点个赞哈。

    extension UITextField {
        func togglePasswordVisibility() {
            isSecureTextEntry = !isSecureTextEntry
            let existingTintColor = tintColor
            tintColor = .clear
            if let existingText = text, isSecureTextEntry {
                /* When toggling to secure text, all text will be purged if the user
                 continues typing unless we intervene. This is prevented by first
                 deleting the existing text and then recovering the original text. */
                deleteBackward()
    
                if let textRange = textRange(from: beginningOfDocument, to: endOfDocument) {
                    replace(textRange, withText: existingText)
                }
            }
    
            /* Reset the selected text range since the cursor can end up in the wrong
             position after a toggle because the text might vary in width */
            if let existingSelectedTextRange = selectedTextRange {
                selectedTextRange = nil
                selectedTextRange = existingSelectedTextRange
            }
            self.tintColor = existingTintColor
        }
    }
    

    相关文章

      网友评论

          本文标题:UITextField 密码明文密文切换光标以及清空问题解决方案

          本文链接:https://www.haomeiwen.com/subject/fkrltrtx.html