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

2021-11-17  本文已影响0人  wenju

不的不说某度找了半天解决都不行,最后还是在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
    }
}
上一篇下一篇

猜你喜欢

热点阅读