不的不说某度找了半天解决都不行,最后还是在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
}
}
网友评论