How to toggle a UITextField secure text entry (hide password) in Swift?

前端 未结 24 2587
时光取名叫无心
时光取名叫无心 2021-01-30 02:00

I currently have a UITextfield with an eye icon in it that when pressed is supposed to toggle the secure text entry on and off.

I know you can che

24条回答
  •  旧时难觅i
    2021-01-30 03:04

    Swift 4 solution

    You don't need extra if statement for simple toggle isSecureTextEntry property

    func togglePasswordVisibility() {
            password.isSecureTextEntry = !password.isSecureTextEntry
        }
    

    But there is a problem when you toggle isSecureTextEntry UITextField doesn't recalculate text width and we have extra space to the right of the text. To avoid this you should replace text this way

    func togglePasswordVisibility() {
            password.isSecureTextEntry = !password.isSecureTextEntry
            if let textRange = password.textRange(from: password.beginningOfDocument, to: password.endOfDocument) {
                password.replace(textRange, withText: password.text!)
            }
        }
    

    UPDATE

    Swift 4.2

    Instead of

    password.isSecureTextEntry = !password.isSecureTextEntry
    

    you can do this

    password.isSecureTextEntry.toggle()
    

提交回复
热议问题