Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jamestapping/3e7d09e3a1cb27d19c21b28e71194e39 to your computer and use it in GitHub Desktop.
Save jamestapping/3e7d09e3a1cb27d19c21b28e71194e39 to your computer and use it in GitHub Desktop.
UITextField+SecureToggle.swift
import Foundation
import UIKit
let button = UIButton(type: .custom)
extension UITextField {
func enablePasswordToggle(){
button.setImage(UIImage(named: "icons8-open-eye-48"), for: .normal)
button.setImage(UIImage(named: "icons8-closed-eye-48"), for: .selected)
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -12, bottom: 0, right: 0)
button.addTarget(self, action: #selector(togglePasswordView), for: .touchUpInside)
rightView = button
rightViewMode = .always
button.alpha = 0.4
}
@objc func togglePasswordView(_ sender: Any) {
isSecureTextEntry.toggle()
button.isSelected.toggle()
}
}
@Blacostnero
Copy link

There's a problem if you want to set more than one textfield with this extension in the same view.

I would change it to this:

import Foundation
import UIKit

extension UITextField {
    
    func enablePasswordToggle(){
        
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "icons8-open-eye-48"), for: .normal)
        button.setImage(UIImage(named: "icons8-closed-eye-48"), for: .selected)
        button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -12, bottom: 0, right: 0)
        button.addTarget(self, action: #selector(togglePasswordView), for: .touchUpInside)
        rightView = button
        rightViewMode = .always
        button.alpha = 0.4
    }
    
    @objc func togglePasswordView(_ sender: UIButton) {
        isSecureTextEntry.toggle()
        sender.isSelected.toggle()
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment