import UIKit
class PasswordTextField: UITextField {
private let toggleButton = UIButton(type: .custom)
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
private func setupView() {
isSecureTextEntry = true
borderStyle = .roundedRect
rightViewMode = .always
setupToggleButton()
}
private func setupToggleButton() {
let buttonSize = CGSize(width: 24, height: 24)
toggleButton.setImage(UIImage(systemName: "eye.fill"), for: .normal)
toggleButton.frame = CGRect(origin: .zero, size: buttonSize)
toggleButton.contentMode = .scaleAspectFit
toggleButton.addTarget(self, action: #selector(togglePasswordVisibility), for: .touchUpInside)
rightView = toggleButton
addConstraints()
}
private func addConstraints() {
toggleButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
toggleButton.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -8),
toggleButton.centerYAnchor.constraint(equalTo: self.centerYAnchor),
toggleButton.widthAnchor.constraint(equalToConstant: 24),
toggleButton.heightAnchor.constraint(equalToConstant: 24)
])
}
@objc private func togglePasswordVisibility() {
isSecureTextEntry.toggle()
let imageName = isSecureTextEntry ? "eye.fill" : "eye.slash.fill"
toggleButton.setImage(UIImage(systemName: imageName), for: .normal)
}
}
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let passwordTextField = PasswordTextField(frame: CGRect(x: 50, y: 100, width: 200, height: 40))
passwordTextField.placeholder = "Password"
view.addSubview(passwordTextField)
}
}