I have a Text Field and I would like to replace the default dot character to something else when the password is hidden. Is there any way to do this easily?
Swift 5 ready to use, updated version of crifan answer:
import UIKit
class PasswordTextField: UITextField, UITextFieldDelegate {
var realText: String {
didSet {
updateMaskStr()
}
}
let maskChar: Character
init(
frame: CGRect = .zero,
maskChar: Character = "*"
) {
realText = ""
self.maskChar = maskChar
super.init(frame: frame)
setupActions()
setupDelegates()
}
private func setupActions() {
addTarget(self, action: #selector(textFiledEditingChanged(textField:)), for: .editingChanged)
}
private func setupDelegates() {
delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func updateMaskStr(){
//change real text to mask char
var maskStr = ""
for _ in realText {
maskStr += String(self.maskChar)
}
text = maskStr
}
@objc
private func textFiledEditingChanged(textField: UITextField) { updateMaskStr() }
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let curText = realText
let updatedStr:String = (curText as NSString).replacingCharacters(in: range, with: string)
realText = updatedStr
return false
}
}