swiftuikituitextfielduitextfielddelegate

How to star part of text field? Like 1234 **** **** 1234


enter image description here

While the user is entering the credit card number, I want to star a certain part of the text field as above for security. How can I do it?


Solution

  • I found the Solution, first of you have to add Delegate for that TextField, After Adding TextField you have to add below code,

    func textFieldDidChangeSelection(_ textField: UITextField) {
        if (textField.text?.count ?? 0) > 4 && (textField.text?.count ?? 0) < 15{
            let firstFourElement = String(self.textFieldEmail.text?.prefix(4) ?? "")
            switch textField.text?.count ?? 0 {
            case 5:
                self.textFieldEmail.text = firstFourElement + " *"
            case 7:
                self.textFieldEmail.text = firstFourElement + " **"
            case 8:
                self.textFieldEmail.text = firstFourElement + " ***"
            case 9:
                self.textFieldEmail.text = firstFourElement + " ****"
            case 10:
                self.textFieldEmail.text = firstFourElement + " **** *"
            case 12:
                self.textFieldEmail.text = firstFourElement + " **** **"
            case 13:
                self.textFieldEmail.text = firstFourElement + " **** ***"
            case 14:
                self.textFieldEmail.text = firstFourElement + " **** **** "
            default:
                print("TEST")
            }
        }
    }