Implemented toggling password visibility

This commit is contained in:
dankito 2020-10-03 07:18:00 +02:00
parent e64e8925c4
commit 8108926d71
1 changed files with 32 additions and 0 deletions

View File

@ -74,6 +74,10 @@ struct UIKitTextField: UIViewRepresentable {
textField.delegate = context.coordinator textField.delegate = context.coordinator
if isPasswordField {
addTogglePasswordVisibilityButton(textField, context.coordinator)
}
// set tag on all TextFields to be able to focus next view (= next tag). See Coordinator for more details // set tag on all TextFields to be able to focus next view (= next tag). See Coordinator for more details
Self.NextTagId = Self.NextTagId + 1 // unbelievable, there's no ++ operator Self.NextTagId = Self.NextTagId + 1 // unbelievable, there's no ++ operator
textField.tag = Self.NextTagId textField.tag = Self.NextTagId
@ -101,6 +105,18 @@ struct UIKitTextField: UIViewRepresentable {
} }
} }
private func addTogglePasswordVisibilityButton(_ textField: UITextField, _ coordinator: Coordinator) {
coordinator.textField = textField
let togglePasswordVisiblityView = UIButton()
togglePasswordVisiblityView.setImage(UIImage(systemName: "eye.slash.fill"), for: .normal)
togglePasswordVisiblityView.tintColor = UIColor.secondaryLabel
togglePasswordVisiblityView.addTarget(coordinator, action:#selector(coordinator.togglePasswordVisibility), for: .touchUpInside)
textField.leftView = togglePasswordVisiblityView
textField.leftViewMode = .always
}
private func addDoneButtonToKeyboard(_ textField: UITextField, _ coordinator: Coordinator) { private func addDoneButtonToKeyboard(_ textField: UITextField, _ coordinator: Coordinator) {
coordinator.textField = textField coordinator.textField = textField
@ -212,6 +228,22 @@ struct UIKitTextField: UIViewRepresentable {
} }
} }
@objc
func togglePasswordVisibility() {
if let textField = self.textField {
textField.isSecureTextEntry.toggle()
if let togglePasswordVisiblityButton = textField.leftView as? UIButton {
if textField.isSecureTextEntry {
togglePasswordVisiblityButton.setImage(UIImage(systemName: "eye.slash.fill"), for: .normal)
}
else {
togglePasswordVisiblityButton.setImage(UIImage(systemName: "eye.fill"), for: .normal)
}
}
}
}
} }
} }