In my project I need to put device MAC address validation while adding text in text field. My device mac address format is “AB:5E:CF:45:S5:6D”. So when ever I will add any character it should be changed with adding colon after 2 character in textfield.
Example : “45DF5R6” = “45:DF:5R:6” “SD45ER65DF6G” = “SD:45:ER:65:DF:6G”
Appreciated your help.
Thanks in advance.
You're looking for delegate function of a UITextField:
You can write input specific logic in that function. It often used for masking phone numbers, or say limiting number of characters added to a textfield. Your formatting issue also fits great.
try this
In
delegate
method ofUITextField
Add a logic that will check length MOD 2 of the string excluding the
character
you want to insert. If you getremainder
equal to0
, add the desiredcharacter
to the string.You should subclass UITextField and add a target for editing changed control event, then you just need to remove the invalid hexa characters and format the cleaned string again using the method to insert a character every two characters in a string as I posted in this answer:
Here is another answer for you. You have to implement the
UITextFieldDelegate
and set thetextField
delegate asself
. Then implement the below delegate method.The logic here is really easy to understand:
shouldChangeCharacters
You should include other logic like character limit, character restrictions, copy-paste handling yourself. The answer just focusses on the logic involved in adding and removing “:”
You do not have to delete the ":" that is inserted when deleting characters. eg: If you have "45:D" and you press delete once, you will be left with "45" and not "45:".