textfield auto focus not working properly - ios

I have 6 text field text box. And when user finish enter in first text field, then it should automatically have to go second and so on. Here my code hats not working. when i enter the value in first text field, the values is entering in second ..here my code :
This below code i have done to enter only one digit in each text field. But here how can i add the text field responder...once i finish with first text field, adn so on...
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == self.cardTextFieldOne{
guard let text = textField.text else {return true}
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= 1
}else if textField == self.cardTextFieldTwo{
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= 1
}
else if textField == self.cardTextFieldTwo{
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= 1
}
else if textField == self.cardTextFieldThree{
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= 1
}
else if textField == self.cardTextFieldFour{
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= 1
}
else if textField == self.cardTextFieldFive{
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= 1
}
else if textField == self.cardTextFieldSix{
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= 1
}
else if textField == self.cardTextFieldMonth{
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= 2
}
else if textField == self.cardTextFieldYear{
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= 2
}
return true
}
Thanks in advance !!
Update
if textField == self.cardTextFieldOne{
guard let text = textField.text else {return true}
let newLength = text.characters.count + string.characters.count - range.length
if (string == "") || string.characters.count < 1
{
return true //This also allow you to backspace
}else if (cardTextFieldOne.text?.characters.count)! >= 1
{
cardTextFieldOne.resignFirstResponder();
self.cardTextFieldTwo.becomeFirstResponder()
return false
}
return newLength <= 1
}

Simple Solution
Create Method which called every time you change the textField text like below you can see in the Image, while you right click on textfield, you see the Editing change drag it and create method like
#IBAction func editing(_ sender: UITextField)
{
if sender == yourFirstTextField {
if sender.text?.characters.count == 1 {
yourNextTextField.becomeFirstResponder()
}
}
}

Try using textField's delegate method
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == self.cardTextFieldOne{
textField.resignFirstResponder();
self.cardTextFieldTwo.becomeFirstResponder();
return false;
}else if textField == self.cardTextFieldTwo{
textField.resignFirstResponder();
self.cardTextFieldThree.becomeFirstResponder()
// if this is last field then return true
return true
}
}

Try to respond manually while textfield fill with single text.
if textField == self.cardTextFieldTwo{
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
if textField.text?.utf16.count==1 { // adjust your condition here
textField.resignFirstResponder()
self.cardTextFieldTwo.becomeFirstResponder()
}
return newLength <= 1
}
Note do this for all textfield

Use textFieldDidEndEditing method, than just call becomeFirstResponder() on next textField
func textFieldDidEndEditing(_ textField: UITextField) {
textField.becomeFirstResponder()
}

Related

Deleting Emoji Bug

I followed this link Find out if Character in String is emoji? to try to limit the amount of characters my text field even with emojis. According to this link, I have to count emojis based on their glyphs and everything is working except for one little bug, when my glyph count is reached, it won't let me delete the string anymore.
Here's the code the handle the character limit using UITextField Delegate
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var canEditString : Bool = false
if textField == self.descTxtField {
// Description Text Field
if textField.text != nil || textField.text != "" {
let currentString = textField.text
if (currentString?.containsEmoji)! {
print("I have an emoji")
let glyphCount = currentString!.glyphCount
print(glyphCount)
canEditString = glyphCount <= descriptionLimit
}else {
print("I have no emoji's")
let currentCharacterCount = textField.text?.characters.count ?? 0
//print(currentCharacterCount)
if (range.length + range.location > currentCharacterCount){
return false
}
let newLength = currentCharacterCount + string.characters.count - range.length
canEditString = newLength <= descriptionLimit
}
}
return canEditString
} else {
// Number Text Field
let currentCharacterCount = textField.text?.characters.count ?? 0
if (range.length + range.location > currentCharacterCount){
return false
}
let newLength = currentCharacterCount + string.characters.count - range.length
return newLength <= numberLimit
}
}
String Manifesto
Swift 4
Emojis now have a character count of 1, making it a lot easier to keep track of character counts in Strings.

Using `textField:shouldChangeCharactersInRange:`, how do i found that characters are mismatch?

I'm using the code below for setting validation of textfield as it should not enter above 15 character length .
let limitLength = 15
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// set maximum length for password and confirm password
if textField == txtPassword { // if textfield password is editing
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= limitLength
} else if textField == txtConfirmpassword { // if textfield confirm password is editing
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= limitLength
}
return true
}
there are two textfield as password and confirm password
i want to check validation whether they have same string or not?
"textField:shouldChangeCharactersInRange" is method we need to use but i don't know how to compare while user is entering and i need to display alert message that they are not same
Note :- it should not compare while click on any button.
try like this
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// set maximum length for password and confirm password
if textField == txtPassword { // if textfield password is editing
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count
return newLength <= limitLength
} else if textField == txtConfirmpassword { // if textfield confirm password is editing
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count
if newLength <= limitLength && txtPassword.text.hasPrefix("\(text)\(string)") {
return true
} else {
// here u can show alert
textField.resignFirstResponder()
return false
}
}
return true
}

Set UITextField to mm-dd-yy format in swift

So I want to have a UITextField to only accept digits, solved that by using a custom keyboard input.
The intention of this UITextField is to get someones birthday. I don't want to use an UIDatePicker tough as I don't like it's appearance.
I'd like that the TextField automatically inserts dashes after every second digit that the user put into the TextField.
dd-mm-yy is the placeholder text. I either thought of making the dashes permanently but I don't know how to do that either.
How can I do this?
You want to allow user to enter text in textfield in this dd-mm-yy right ?
if it so i'am sure this will help you.
In top of your class declare this variable which we gonna use later.
var dateFormate = Bool()
Add delegate and tag for that textfield.
Then add this following delegate method
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
//1. To make sure that this is applicable to only particular textfield add tag.
if textField.tag == 1 {
//2. this one helps to make sure that user enters only numeric characters and '-' in fields
let numbersOnly = NSCharacterSet(charactersInString: "1234567890-")
let characterSetFromTextField = NSCharacterSet(charactersInString: string)
let Validate:Bool = numbersOnly .isSupersetOfSet(characterSetFromTextField)
if !Validate {
return false;
}
if range.length + range.location > textField.text?.characters.count {
return false
}
let newLength = (textField.text?.characters.count)! + string.characters.count - range.length
if newLength == 3 || newLength == 6 {
let char = string.cStringUsingEncoding(NSUTF8StringEncoding)!
let isBackSpace = strcmp(char, "\\b")
if (isBackSpace == -92) {
dateFormate = false;
}else{
dateFormate = true;
}
if dateFormate {
let textContent:String!
textContent = textField.text
//3.Here we add '-' on overself.
let textWithHifen:NSString = "\(textContent)-"
textField.text = textWithHifen as String
dateFormate = false
}
}
//4. this one helps to make sure only 8 character is added in textfield .(ie: dd-mm-yy)
return newLength <= 8;
}
return true
}
That's it now user can enter their DOB.No need to worry about '-' it will be added automatically.
Swift 3:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
//1. To make sure that this is applicable to only particular textfield add tag.
if textField.tag == 1 {
//2. this one helps to make sure that user enters only numeric characters and '-' in fields
let numbersOnly = CharacterSet(charactersIn: "1234567890-")
let Validate = string.rangeOfCharacter(from: numbersOnly.inverted) == nil ? true : false
if !Validate {
return false;
}
if range.length + range.location > textField.text?.characters.count {
return false
}
let newLength = (textField.text?.characters.count)! + string.characters.count - range.length
if newLength == 3 || newLength == 6 {
let char = string.cString(using: NSUTF8StringEncoding)!
let isBackSpace = strcmp(char, "\\b")
if (isBackSpace == -92) {
dateFormate = false;
}else{
dateFormate = true;
}
if dateFormate {
let textContent:String!
textContent = textField.text
//3.Here we add '-' on overself.
let textWithHifen:NSString = "\(textContent)-"
textField.text = textWithHifen as String
dateFormate = false
}
}
//4. this one helps to make sure only 8 character is added in textfield .(ie: dd-mm-yy)
return newLength <= 8;
}
return true
}
Swift5
// Use textfield delegate shouldChangeCharactersIn
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if (textField.text?.count == 2) || (textField.text?.count == 5) {
if !(string == "") {
textField.text = (textField.text)! + "-"
}
}
return !(textField.text!.count > 7 && (string.count ) > range.length)
}

Best way to force a text field to have a single word only in swift? [duplicate]

I have a Verification ViewController, I get 4 digit verification code by SMS and I need to enter those code to login, I have created the ViewController like this
As you can see four UITextFields, I need to allow only single digit for each UITextField,
What I tried: I was trying to use shouldChangeCharactersInRange:method: , but its not getting called, I don't know what's wrong, I think because UITextFields are in UITableView so it is not working.
You can change the text field like this by using the delegate function of the text field. Initially, you need to set the delegate and the tag of each text field.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ((textField.text.length >= 1) && (string.length > 0))
{
NSInteger nextTag = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (! nextResponder)
nextResponder = [textField.superview viewWithTag:1];
if (nextResponder)
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
return NO;
}
return YES;
}
Swift 2
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// On inputing value to textfield
if (textField.text?.characters.count < 1 && string.characters.count > 0){
let nextTag = textField.tag + 1;
// get next responder
var nextResponder = textField.superview?.viewWithTag(nextTag);
if (nextResponder == nil){
nextResponder = textField.superview?.viewWithTag(1);
}
textField.text = string;
nextResponder?.becomeFirstResponder();
return false;
}
else if (textField.text?.characters.count >= 1 && string.characters.count == 0){
// on deleting value from Textfield
let previousTag = textField.tag - 1;
// get next responder
var previousResponder = textField.superview?.viewWithTag(previousTag);
if (previousResponder == nil){
previousResponder = textField.superview?.viewWithTag(1);
}
textField.text = "";
previousResponder?.becomeFirstResponder();
return false;
}
return true;
}
Swift 4
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField.text!.count < 1 && string.count > 0{
let nextTag = textField.tag + 1
// get next responder
var nextResponder = textField.superview?.viewWithTag(nextTag)
if (nextResponder == nil){
nextResponder = textField.superview?.viewWithTag(1)
}
textField.text = string
nextResponder?.becomeFirstResponder()
return false
}
else if textField.text!.count >= 1 && string.count == 0{
// on deleting value from Textfield
let previousTag = textField.tag - 1
// get next responder
var previousResponder = textField.superview?.viewWithTag(previousTag)
if (previousResponder == nil){
previousResponder = textField.superview?.viewWithTag(1)
}
textField.text = ""
previousResponder?.becomeFirstResponder()
return false
}
return true
}
Use this code if you don't want to work with tag and it works better then above
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// On inputing value to textfield
if ((textField.text?.characters.count)! < 1 && string.characters.count > 0){
if(textField == txtOne)
{
txtTwo.becomeFirstResponder()
}
if(textField == txtTwo)
{
txtThree.becomeFirstResponder()
}
if(textField == txtThree)
{
txtFour.becomeFirstResponder()
}
textField.text = string
return false
}
else if ((textField.text?.characters.count)! >= 1 && string.characters.count == 0){
// on deleting value from Textfield
if(textField == txtTwo)
{
txtOne.becomeFirstResponder()
}
if(textField == txtThree)
{
txtTwo.becomeFirstResponder()
}
if(textField == txtFour)
{
txtThree.becomeFirstResponder()
}
textField.text = ""
return false
}
else if ((textField.text?.characters.count)! >= 1 )
{
textField.text = string
return false
}
return true
}
Swift 4
Inspired by #Anurag Soni and #Varun Naharia answers
Variant A
extension EnterConfirmationCodeTextField: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldCount = textField.text?.count else { return false }
// Сlosure
let setValueAndMoveForward = {
textField.text = string
let nextTag = textField.tag + 1
if let nextResponder = textField.superview?.viewWithTag(nextTag) {
nextResponder.becomeFirstResponder()
}
}
// Сlosure
let clearValueAndMoveBack = {
textField.text = ""
let previousTag = textField.tag - 1
if let previousResponder = textField.superview?.viewWithTag(previousTag) {
previousResponder.becomeFirstResponder()
}
}
if textFieldCount < 1 && string.count > 0 {
setValueAndMoveForward()
if textField.tag == 4 {
print("Do something")
}
return false
} else if textFieldCount >= 1 && string.count == 0 {
clearValueAndMoveBack()
return false
} else if textFieldCount >= 1 && string.count > 0 {
let nextTag = self.tag + 1
if let previousResponder = self.superview?.viewWithTag(nextTag) {
previousResponder.becomeFirstResponder()
if let activeTextField = previousResponder as? UITextField {
activeTextField.text = string
}
}
return false
}
return true
}
}
Variant B (a little bit another behavior):
extension EnterConfirmationCodeTextField: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldCount = textField.text?.count else { return false }
// Сlosure
let setValueAndMoveForward = {
textField.text = string
let nextTag = textField.tag + 1
if let nextResponder = textField.superview?.viewWithTag(nextTag) {
nextResponder.becomeFirstResponder()
}
}
// Сlosure
let clearValueAndMoveBack = {
textField.text = ""
let previousTag = textField.tag - 1
if let previousResponder = textField.superview?.viewWithTag(previousTag) {
previousResponder.becomeFirstResponder()
}
}
if textFieldCount < 1 && string.count > 0 {
setValueAndMoveForward()
if textField.tag == 4 {
print("Do something")
}
return false
} else if textFieldCount >= 1 && string.count == 0 {
clearValueAndMoveBack()
return false
} else if textFieldCount >= 1 {
setValueAndMoveForward()
return false
}
return true
}
}
Also, I implemented this feature:
In the case where the last textFiled is empty, I just want to switch to the previous textFiled. I tried all this methods. But as for me the method below more elegant and works like a charm:
Variant A
class EnterConfirmationCodeTextField: UITextField {
// MARK: Life cycle
override func awakeFromNib() {
super.awakeFromNib()
delegate = self
}
// MARK: Methods
override func deleteBackward() {
super.deleteBackward()
let previousTag = self.tag - 1
if let previousResponder = self.superview?.viewWithTag(previousTag) {
previousResponder.becomeFirstResponder()
if let activeTextField = previousResponder as? UITextField {
if let isEmpty = activeTextField.text?.isEmpty, !isEmpty {
activeTextField.text = String()
}
}
}
}
}
Variant B (a little bit another behavior):
class EnterConfirmationCodeTextField: UITextField {
// MARK: Life cycle
override func awakeFromNib() {
super.awakeFromNib()
delegate = self
}
// MARK: Methods
override func deleteBackward() {
super.deleteBackward()
let previousTag = self.tag - 1
if let previousResponder = self.superview?.viewWithTag(previousTag) {
previousResponder.becomeFirstResponder()
}
}
}
Assign EnterConfirmationCodeTextField for each of your textFields and set they appropriate tag value.
I have taken one Hidden text field & four imageViews for that with two images. One for Blank and other for Bullet same as iOS default.
Also set tags for four imageviews.
On Load set Focus for Pin Code
- (void)startPinCode
{
txtPinCodeLockDigits.text = #"";
for (int i = 1; i <= 4; i++) {
UIImageView *img = (UIImageView *)[self.view viewWithTag:i];
[img setImage:[UIImage imageNamed:#"Img_BG_PinCode.png"]];
}
[txtPinCodeLockDigits becomeFirstResponder];
}
Then change imageview's images as per user input and only allow four characters
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *result = [textField.text stringByReplacingCharactersInRange:range withString:string];
textField.text = result;
for (int i = 1; i <= 4; i++) {
UIImageView *img = (UIImageView *)[self.view viewWithTag:i];
if (i <= [result length])
[img setImage:[UIImage imageNamed:#"Img_BG_PinCode_Filled.png"]];
else
[img setImage:[UIImage imageNamed:#"Img_BG_PinCode.png"]];
}
NSLog(#"Result :: %#", result);
if ([result length] == 4) {
[self performSelector:#selector(keyGenerationForApplication:) withObject:result afterDelay:0.2];
}
return NO;
}
After Four characters call function for generated PIN Code and store it in User Defaults same as iOS default PIN settings
- (void)keyGenerationForApplication:(NSString *)pinCode
{
int appCode = [pinCode intValue];
[DefaultsValues setIntegerValueToUserDefaults:appCode ForKey:PIN_LOCK_PATTERN];
}
Here, you can again call StartPinCode method for re-confirming code.
Hopefully, it'll help you.
Thanks
It can be achieve using UITextField delegate & by setting Tag for each Textfield in increasing order (say 1 - 4), below is the delegate handler to solve the issue.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// On inputing value to textfield
if (textField.text?.characters.count < 1 && string.characters.count > 0){
let nextTag = textField.tag + 1;
// get next responder
var nextResponder = textField.superview?.viewWithTag(nextTag);
if (nextResponder == nil){
nextResponder = textField.superview?.viewWithTag(1);
}
textField.text = string;
nextResponder?.becomeFirstResponder();
return false;
}
else if (textField.text?.characters.count >= 1 && string.characters.count == 0){
// on deleteing value from Textfield
let previousTag = textField.tag - 1;
// get next responder
var previousResponder = textField.superview?.viewWithTag(previousTag);
if (previousResponder == nil){
previousResponder = textField.superview?.viewWithTag(1);
}
textField.text = "";
previousResponder?.becomeFirstResponder();
return false;
}
return true;
}
swift 2.3
class BankDepositsWithOTPVC: UIViewController {
let limitLength = 1
override func viewDidLoad() {
super.viewDidLoad()
}
}
// MARK: Textfield Validator
extension BankDepositsWithOTPVC : UITextFieldDelegate {
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// On inputing value to textfield
if (textField.text?.characters.count < 1 && string.characters.count > 0){
let nextTag = textField.tag + 1;
// get next responder
let nextResponder = textField.superview?.viewWithTag(nextTag);
if (nextResponder == nil){
textField.resignFirstResponder()
// nextResponder = textField.superview?.viewWithTag(1);
}
textField.text = string;
nextResponder?.becomeFirstResponder();
return false;
}else if (textField.text?.characters.count >= 1 && string.characters.count > 0){
// maximum 1 digit
textField.text = "";
let nextTag = textField.tag + 1;
// get next responder
let nextResponder = textField.superview?.viewWithTag(nextTag);
if (nextResponder == nil){
textField.resignFirstResponder()
// nextResponder = textField.superview?.viewWithTag(1);
}
textField.text = string;
nextResponder?.becomeFirstResponder();
return false;
}
else if (textField.text?.characters.count >= 1 && string.characters.count == 0){
// on deleteing value from Textfield
let previousTag = textField.tag - 1;
// get next responder
var previousResponder = textField.superview?.viewWithTag(previousTag);
if (previousResponder == nil){
previousResponder = textField.superview?.viewWithTag(1);
}
textField.text = "";
previousResponder?.becomeFirstResponder();
return false;
}
//return true;
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= limitLength
}
}
Objective-C
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if ((textField.text.length < 1) && (string.length > 0))
{
NSInteger nextTag = textField.tag + 1;
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (! nextResponder){
[textField resignFirstResponder];
}
textField.text = string;
if (nextResponder)
[nextResponder becomeFirstResponder];
return NO;
}else if ((textField.text.length >= 1) && (string.length > 0)){
//FOR MAXIMUM 1 TEXT
NSInteger nextTag = textField.tag + 1;
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (! nextResponder){
[textField resignFirstResponder];
}
textField.text = string;
if (nextResponder)
[nextResponder becomeFirstResponder];
return NO;
}
else if ((textField.text.length >= 1) && (string.length == 0)){
// on deleteing value from Textfield
NSInteger prevTag = textField.tag - 1;
// Try to find prev responder
UIResponder* prevResponder = [textField.superview viewWithTag:prevTag];
if (! prevResponder){
[textField resignFirstResponder];
}
textField.text = string;
if (prevResponder)
// Found next responder, so set it.
[prevResponder becomeFirstResponder];
return NO;
}
return YES;
}
Modified Anurag Soni's answer in Swift 3.
It assumes you have outlet collection named textFields and the text fields have ordered tags set
It adds case when there's already some digit in text field and when user types something new - the digit is replaced
Input is restricted to digits only
It prevents from pasting more than one digit
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Restrict to only digits
let aSet = NSCharacterSet(charactersIn:"0123456789").inverted
let compSepByCharInSet = string.components(separatedBy: aSet)
let numberFiltered = compSepByCharInSet.joined(separator: "")
if string != numberFiltered {
return false
}
// Get the unwrapped text
guard let text = textField.text else {
return false
}
if (text.characters.count < 1 && string.characters.count == 1) {
// New value to empty text field
textField.text = string
// Next responder
if let someTextField = (textFields.filter { $0.tag == textField.tag + 1 }).first {
someTextField.becomeFirstResponder()
} else {
view.endEditing(true)
}
return false
} else if (text.characters.count >= 1 && string.characters.count == 0){
// On deleting value from Textfield
textField.text = ""
// Previous responder
if let someTextField = (textFields.filter { $0.tag == textField.tag - 1 }).first {
someTextField.becomeFirstResponder()
} else {
view.endEditing(true)
}
return false
} else if string.characters.count == 1 {
// There's already some digit in text field
// Replace it with new one
textField.text = string
// Next responder
if let someTextField = (textFields.filter { $0.tag == textField.tag + 1 }).first {
someTextField.becomeFirstResponder()
} else {
view.endEditing(true)
}
}
return false
}
Provide the tag to the textfield like 1,2,3,4 and directly use it
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
let next:NSInteger
if string == "" {
next = textField.tag - 1;
}
else{
next = textField.tag + 1;
}
if (textField.text?.characters.count)! >= 1 {
if textField.tag == 4 {
if string == "" {
textField.text = ""
let temptf = self.view.viewWithTag(next) as! UITextField
temptf.becomeFirstResponder()
return false
}
else{
if (textField.text?.characters.count)! > 1 {
let stringg = textField.text!
textField.text = stringg.replacingOccurrences(of: stringg, with: string)
}
return false
}
}
else{
if string == "" {
textField.text = ""
if next != 0 {
let temptf = self.view.viewWithTag(next) as! UITextField
temptf.becomeFirstResponder()
}
return false
}
else{
if (textField.text?.characters.count)! > 1 {
let stringg = textField.text!
textField.text = stringg.replacingOccurrences(of: stringg, with: string)
}
let temptf = self.view.viewWithTag(next) as! UITextField
temptf.becomeFirstResponder()
}
}
}
return true
}
Swift 4
when you input a number from the pin code into a text field, you should let a number be shown and then the next text field will become the first responder, so change the first responder after the code was in the text view
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textField = textField as? PinCodeTextField else { return true }
if string == "" {// when the backward clicked, let it go :)
return true
}
// when textfield is not empty, well, next number
if textField.pinCode.count == textField.maxCount {
becomeFirstResponder(after: textField)
return false
}
if string.count > textField.maxCharacterCount {// the max character count should be 1
return false
}
return true
}
// now the text field has been filled with a number
func textFieldCotentDidChange(_ textField: UITextField) {
print("didchange")
guard let textField = textField as? PinCodeTextField else { return }
if textField.pinCode.count == 0 {
becomeFirstResponder(before: textField)
}
// when textfield has been filled, ok! next!
if textField.pinCode.count == textField.maxCharacterCount {
becomeFirstResponder(after: textField)
}
}
for more details and the simple demo, see this link
Try this
sample tutorial passcode lock
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UITextFieldDelegate>
{
IBOutlet UITextField *txtPassword;
}
#end
ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
txtPassword.delegate=self;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 1) ? NO : YES;
}
Just use TextFieldDelegate method and check the length of the TextField after every changes
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
if newString.characters.count == 1
{
nextTextField.becomeFirstResponder()
return true
}
else
{
return false
}
}
I was working on a similar functionality and did it in my way. Solution below.
Swift 4
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//For clear button pressed
//If the textfield has already text in it
if string.count == 0 {
textField.text = string
return true
}
//For First time entry into the text field
guard let text = textField.text, text.count <= 0 else {
//If user enter second character
return false
}
//For First time entry into the text field
if text.count == 0 {
textField.text = string
textField.resignFirstResponder()
self.nextResponde(tag: textField.tag)
return true
}
return false
}
//To make the next field as responder
func nextResponde(tag: Int) {
switch tag {
case self.PINTextField.tag:
guard let text = self.PINTextField1.text, text.count == 1 else {
self.PINTextField1.becomeFirstResponder()
return
}
case self.PINTextField1.tag:
guard let text = self.PINTextField2.text, text.count == 1 else {
self.PINTextField2.becomeFirstResponder()
return
}
case self.PINTextField2.tag:
guard let text = self.PINTextField3.text, text.count == 1 else {
self.PINTextField3.becomeFirstResponder()
return
}
default:
let _ = tag
}
}
Credit to #Anurag Soni, here's an alternate UX pushing onto the next field and dismissing upon completion (with layout logic also above):
-(UIView *)addSpacedTextInputToView:(UIView *)parent subtitle:(NSString *)subtitle spaces:(int)spaces atOffset:(float)offset{
float parentWidth = parent.frame.size.width;
float tfWidth = 2 * increment;
float tfHeight = 3 * increment;
float startX = 3 * increment;
float remainingWidth = parentWidth - 2 * startX - spaces * tfWidth;
float padding = remainingWidth / (float)(spaces-1);
UIView * holder = [self addViewToView:parent withFrame:CGRectMake(0, offset, parentWidth, 0)];
UIView * tfHolder = [self addViewToView:holder withFrame:CGRectMake(0, 0, parentWidth, tfHeight)];
float localX = startX;
float localY = 0.0f;
for (int n = 0; n < spaces; n++){
UITextField * tf = [UITextField new];
tf.frame = CGRectMake(localX, localY, tfWidth, tfHeight);
tf.textColor = [UIColor whiteColor];
tf.font = headerFont;
tf.textAlignment = NSTextAlignmentCenter;
tf.tintColor = [UIColor whiteColor];
tf.keyboardAppearance = UIKeyboardAppearanceDark;
tf.tag = n;
tf.delegate = self;
[tfHolder addSubview:tf];
UIView * div = [self addViewToView:tf withFrame:CGRectMake(0, tfHeight-2, tfWidth, 1)];
div.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.5f];
localX += tfWidth;
localX += padding;
}
localY += tfHeight;
localY += increment;
localY += [self addSystemLabelToView:holder colour:nil text:subtitle maxWidth:0 offset:localY].frame.size.height;
holder.frame = CGRectMake(0, offset, parent.frame.size.width, localY);
return holder;
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (string.length > 0){
textField.text = string.uppercaseString; //optional to uppercase
UIView * div = textField.subviews.firstObject; //change div colour
div.backgroundColor = [UIColor whiteColor];
int nextTag = (int)textField.tag + 1;
UIResponder * nextResponder = [textField.superview viewWithTag:nextTag];
if (!nextResponder){
[textField resignFirstResponder];
}
if (nextResponder){
[nextResponder becomeFirstResponder];
}
}
return false;
}
Objective-c answer of Varun Naharia solution.
Solution using IBOutletCollections
#property (strong, nonatomic) IBOutletCollection(UITextField) NSArray *otpTextFields;
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField.text.length < 1 && string.length > 0) {
for(int i=0; i<self.otpTextFields.count-1; i++) {
if(textField == self.otpTextFields[i]) {
UITextField* nextTextField = (UITextField*) self.otpTextFields[i+1];
[nextTextField becomeFirstResponder];
}
}
textField.text = string;
return NO;
} else if (textField.text.length >= 1 && string.length == 0) {
for(int i=(int) self.otpTextFields.count-1;i>=1;i--) {
if(textField == self.otpTextFields[i]) {
UITextField* nextTextField = (UITextField*) self.otpTextFields[i-1];
[nextTextField becomeFirstResponder];
}
}
textField.text = #"";
return NO;
} else if(textField.text.length >= 1){
textField.text = string;
return NO;
}
return YES;
}
try this : - For swift 3.0
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// On inputing value to textfield
if ((textField.text?.characters.count)! < 1 && string.characters.count > 0){
let nextTag = textField.tag + 1;
// get next responder
let nextResponder = textField.superview?.viewWithTag(nextTag);
textField.text = string;
if (nextResponder == nil){
textField.resignFirstResponder()
}
nextResponder?.becomeFirstResponder();
return false;
}
else if ((textField.text?.characters.count)! >= 1 && string.characters.count == 0){
// on deleting value from Textfield
let previousTag = textField.tag - 1;
// get next responder
var previousResponder = textField.superview?.viewWithTag(previousTag);
if (previousResponder == nil){
previousResponder = textField.superview?.viewWithTag(1);
}
textField.text = "";
previousResponder?.becomeFirstResponder();
return false;
}
return true;
}
converted Anurag Soni answer in swift 3.0
You just have to implement this method only.

Allowing single digit in UITextField in iOS

I have a Verification ViewController, I get 4 digit verification code by SMS and I need to enter those code to login, I have created the ViewController like this
As you can see four UITextFields, I need to allow only single digit for each UITextField,
What I tried: I was trying to use shouldChangeCharactersInRange:method: , but its not getting called, I don't know what's wrong, I think because UITextFields are in UITableView so it is not working.
You can change the text field like this by using the delegate function of the text field. Initially, you need to set the delegate and the tag of each text field.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ((textField.text.length >= 1) && (string.length > 0))
{
NSInteger nextTag = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (! nextResponder)
nextResponder = [textField.superview viewWithTag:1];
if (nextResponder)
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
return NO;
}
return YES;
}
Swift 2
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// On inputing value to textfield
if (textField.text?.characters.count < 1 && string.characters.count > 0){
let nextTag = textField.tag + 1;
// get next responder
var nextResponder = textField.superview?.viewWithTag(nextTag);
if (nextResponder == nil){
nextResponder = textField.superview?.viewWithTag(1);
}
textField.text = string;
nextResponder?.becomeFirstResponder();
return false;
}
else if (textField.text?.characters.count >= 1 && string.characters.count == 0){
// on deleting value from Textfield
let previousTag = textField.tag - 1;
// get next responder
var previousResponder = textField.superview?.viewWithTag(previousTag);
if (previousResponder == nil){
previousResponder = textField.superview?.viewWithTag(1);
}
textField.text = "";
previousResponder?.becomeFirstResponder();
return false;
}
return true;
}
Swift 4
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField.text!.count < 1 && string.count > 0{
let nextTag = textField.tag + 1
// get next responder
var nextResponder = textField.superview?.viewWithTag(nextTag)
if (nextResponder == nil){
nextResponder = textField.superview?.viewWithTag(1)
}
textField.text = string
nextResponder?.becomeFirstResponder()
return false
}
else if textField.text!.count >= 1 && string.count == 0{
// on deleting value from Textfield
let previousTag = textField.tag - 1
// get next responder
var previousResponder = textField.superview?.viewWithTag(previousTag)
if (previousResponder == nil){
previousResponder = textField.superview?.viewWithTag(1)
}
textField.text = ""
previousResponder?.becomeFirstResponder()
return false
}
return true
}
Use this code if you don't want to work with tag and it works better then above
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// On inputing value to textfield
if ((textField.text?.characters.count)! < 1 && string.characters.count > 0){
if(textField == txtOne)
{
txtTwo.becomeFirstResponder()
}
if(textField == txtTwo)
{
txtThree.becomeFirstResponder()
}
if(textField == txtThree)
{
txtFour.becomeFirstResponder()
}
textField.text = string
return false
}
else if ((textField.text?.characters.count)! >= 1 && string.characters.count == 0){
// on deleting value from Textfield
if(textField == txtTwo)
{
txtOne.becomeFirstResponder()
}
if(textField == txtThree)
{
txtTwo.becomeFirstResponder()
}
if(textField == txtFour)
{
txtThree.becomeFirstResponder()
}
textField.text = ""
return false
}
else if ((textField.text?.characters.count)! >= 1 )
{
textField.text = string
return false
}
return true
}
Swift 4
Inspired by #Anurag Soni and #Varun Naharia answers
Variant A
extension EnterConfirmationCodeTextField: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldCount = textField.text?.count else { return false }
// Сlosure
let setValueAndMoveForward = {
textField.text = string
let nextTag = textField.tag + 1
if let nextResponder = textField.superview?.viewWithTag(nextTag) {
nextResponder.becomeFirstResponder()
}
}
// Сlosure
let clearValueAndMoveBack = {
textField.text = ""
let previousTag = textField.tag - 1
if let previousResponder = textField.superview?.viewWithTag(previousTag) {
previousResponder.becomeFirstResponder()
}
}
if textFieldCount < 1 && string.count > 0 {
setValueAndMoveForward()
if textField.tag == 4 {
print("Do something")
}
return false
} else if textFieldCount >= 1 && string.count == 0 {
clearValueAndMoveBack()
return false
} else if textFieldCount >= 1 && string.count > 0 {
let nextTag = self.tag + 1
if let previousResponder = self.superview?.viewWithTag(nextTag) {
previousResponder.becomeFirstResponder()
if let activeTextField = previousResponder as? UITextField {
activeTextField.text = string
}
}
return false
}
return true
}
}
Variant B (a little bit another behavior):
extension EnterConfirmationCodeTextField: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldCount = textField.text?.count else { return false }
// Сlosure
let setValueAndMoveForward = {
textField.text = string
let nextTag = textField.tag + 1
if let nextResponder = textField.superview?.viewWithTag(nextTag) {
nextResponder.becomeFirstResponder()
}
}
// Сlosure
let clearValueAndMoveBack = {
textField.text = ""
let previousTag = textField.tag - 1
if let previousResponder = textField.superview?.viewWithTag(previousTag) {
previousResponder.becomeFirstResponder()
}
}
if textFieldCount < 1 && string.count > 0 {
setValueAndMoveForward()
if textField.tag == 4 {
print("Do something")
}
return false
} else if textFieldCount >= 1 && string.count == 0 {
clearValueAndMoveBack()
return false
} else if textFieldCount >= 1 {
setValueAndMoveForward()
return false
}
return true
}
}
Also, I implemented this feature:
In the case where the last textFiled is empty, I just want to switch to the previous textFiled. I tried all this methods. But as for me the method below more elegant and works like a charm:
Variant A
class EnterConfirmationCodeTextField: UITextField {
// MARK: Life cycle
override func awakeFromNib() {
super.awakeFromNib()
delegate = self
}
// MARK: Methods
override func deleteBackward() {
super.deleteBackward()
let previousTag = self.tag - 1
if let previousResponder = self.superview?.viewWithTag(previousTag) {
previousResponder.becomeFirstResponder()
if let activeTextField = previousResponder as? UITextField {
if let isEmpty = activeTextField.text?.isEmpty, !isEmpty {
activeTextField.text = String()
}
}
}
}
}
Variant B (a little bit another behavior):
class EnterConfirmationCodeTextField: UITextField {
// MARK: Life cycle
override func awakeFromNib() {
super.awakeFromNib()
delegate = self
}
// MARK: Methods
override func deleteBackward() {
super.deleteBackward()
let previousTag = self.tag - 1
if let previousResponder = self.superview?.viewWithTag(previousTag) {
previousResponder.becomeFirstResponder()
}
}
}
Assign EnterConfirmationCodeTextField for each of your textFields and set they appropriate tag value.
I have taken one Hidden text field & four imageViews for that with two images. One for Blank and other for Bullet same as iOS default.
Also set tags for four imageviews.
On Load set Focus for Pin Code
- (void)startPinCode
{
txtPinCodeLockDigits.text = #"";
for (int i = 1; i <= 4; i++) {
UIImageView *img = (UIImageView *)[self.view viewWithTag:i];
[img setImage:[UIImage imageNamed:#"Img_BG_PinCode.png"]];
}
[txtPinCodeLockDigits becomeFirstResponder];
}
Then change imageview's images as per user input and only allow four characters
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *result = [textField.text stringByReplacingCharactersInRange:range withString:string];
textField.text = result;
for (int i = 1; i <= 4; i++) {
UIImageView *img = (UIImageView *)[self.view viewWithTag:i];
if (i <= [result length])
[img setImage:[UIImage imageNamed:#"Img_BG_PinCode_Filled.png"]];
else
[img setImage:[UIImage imageNamed:#"Img_BG_PinCode.png"]];
}
NSLog(#"Result :: %#", result);
if ([result length] == 4) {
[self performSelector:#selector(keyGenerationForApplication:) withObject:result afterDelay:0.2];
}
return NO;
}
After Four characters call function for generated PIN Code and store it in User Defaults same as iOS default PIN settings
- (void)keyGenerationForApplication:(NSString *)pinCode
{
int appCode = [pinCode intValue];
[DefaultsValues setIntegerValueToUserDefaults:appCode ForKey:PIN_LOCK_PATTERN];
}
Here, you can again call StartPinCode method for re-confirming code.
Hopefully, it'll help you.
Thanks
It can be achieve using UITextField delegate & by setting Tag for each Textfield in increasing order (say 1 - 4), below is the delegate handler to solve the issue.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// On inputing value to textfield
if (textField.text?.characters.count < 1 && string.characters.count > 0){
let nextTag = textField.tag + 1;
// get next responder
var nextResponder = textField.superview?.viewWithTag(nextTag);
if (nextResponder == nil){
nextResponder = textField.superview?.viewWithTag(1);
}
textField.text = string;
nextResponder?.becomeFirstResponder();
return false;
}
else if (textField.text?.characters.count >= 1 && string.characters.count == 0){
// on deleteing value from Textfield
let previousTag = textField.tag - 1;
// get next responder
var previousResponder = textField.superview?.viewWithTag(previousTag);
if (previousResponder == nil){
previousResponder = textField.superview?.viewWithTag(1);
}
textField.text = "";
previousResponder?.becomeFirstResponder();
return false;
}
return true;
}
swift 2.3
class BankDepositsWithOTPVC: UIViewController {
let limitLength = 1
override func viewDidLoad() {
super.viewDidLoad()
}
}
// MARK: Textfield Validator
extension BankDepositsWithOTPVC : UITextFieldDelegate {
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// On inputing value to textfield
if (textField.text?.characters.count < 1 && string.characters.count > 0){
let nextTag = textField.tag + 1;
// get next responder
let nextResponder = textField.superview?.viewWithTag(nextTag);
if (nextResponder == nil){
textField.resignFirstResponder()
// nextResponder = textField.superview?.viewWithTag(1);
}
textField.text = string;
nextResponder?.becomeFirstResponder();
return false;
}else if (textField.text?.characters.count >= 1 && string.characters.count > 0){
// maximum 1 digit
textField.text = "";
let nextTag = textField.tag + 1;
// get next responder
let nextResponder = textField.superview?.viewWithTag(nextTag);
if (nextResponder == nil){
textField.resignFirstResponder()
// nextResponder = textField.superview?.viewWithTag(1);
}
textField.text = string;
nextResponder?.becomeFirstResponder();
return false;
}
else if (textField.text?.characters.count >= 1 && string.characters.count == 0){
// on deleteing value from Textfield
let previousTag = textField.tag - 1;
// get next responder
var previousResponder = textField.superview?.viewWithTag(previousTag);
if (previousResponder == nil){
previousResponder = textField.superview?.viewWithTag(1);
}
textField.text = "";
previousResponder?.becomeFirstResponder();
return false;
}
//return true;
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= limitLength
}
}
Objective-C
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if ((textField.text.length < 1) && (string.length > 0))
{
NSInteger nextTag = textField.tag + 1;
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (! nextResponder){
[textField resignFirstResponder];
}
textField.text = string;
if (nextResponder)
[nextResponder becomeFirstResponder];
return NO;
}else if ((textField.text.length >= 1) && (string.length > 0)){
//FOR MAXIMUM 1 TEXT
NSInteger nextTag = textField.tag + 1;
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (! nextResponder){
[textField resignFirstResponder];
}
textField.text = string;
if (nextResponder)
[nextResponder becomeFirstResponder];
return NO;
}
else if ((textField.text.length >= 1) && (string.length == 0)){
// on deleteing value from Textfield
NSInteger prevTag = textField.tag - 1;
// Try to find prev responder
UIResponder* prevResponder = [textField.superview viewWithTag:prevTag];
if (! prevResponder){
[textField resignFirstResponder];
}
textField.text = string;
if (prevResponder)
// Found next responder, so set it.
[prevResponder becomeFirstResponder];
return NO;
}
return YES;
}
Modified Anurag Soni's answer in Swift 3.
It assumes you have outlet collection named textFields and the text fields have ordered tags set
It adds case when there's already some digit in text field and when user types something new - the digit is replaced
Input is restricted to digits only
It prevents from pasting more than one digit
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Restrict to only digits
let aSet = NSCharacterSet(charactersIn:"0123456789").inverted
let compSepByCharInSet = string.components(separatedBy: aSet)
let numberFiltered = compSepByCharInSet.joined(separator: "")
if string != numberFiltered {
return false
}
// Get the unwrapped text
guard let text = textField.text else {
return false
}
if (text.characters.count < 1 && string.characters.count == 1) {
// New value to empty text field
textField.text = string
// Next responder
if let someTextField = (textFields.filter { $0.tag == textField.tag + 1 }).first {
someTextField.becomeFirstResponder()
} else {
view.endEditing(true)
}
return false
} else if (text.characters.count >= 1 && string.characters.count == 0){
// On deleting value from Textfield
textField.text = ""
// Previous responder
if let someTextField = (textFields.filter { $0.tag == textField.tag - 1 }).first {
someTextField.becomeFirstResponder()
} else {
view.endEditing(true)
}
return false
} else if string.characters.count == 1 {
// There's already some digit in text field
// Replace it with new one
textField.text = string
// Next responder
if let someTextField = (textFields.filter { $0.tag == textField.tag + 1 }).first {
someTextField.becomeFirstResponder()
} else {
view.endEditing(true)
}
}
return false
}
Provide the tag to the textfield like 1,2,3,4 and directly use it
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
let next:NSInteger
if string == "" {
next = textField.tag - 1;
}
else{
next = textField.tag + 1;
}
if (textField.text?.characters.count)! >= 1 {
if textField.tag == 4 {
if string == "" {
textField.text = ""
let temptf = self.view.viewWithTag(next) as! UITextField
temptf.becomeFirstResponder()
return false
}
else{
if (textField.text?.characters.count)! > 1 {
let stringg = textField.text!
textField.text = stringg.replacingOccurrences(of: stringg, with: string)
}
return false
}
}
else{
if string == "" {
textField.text = ""
if next != 0 {
let temptf = self.view.viewWithTag(next) as! UITextField
temptf.becomeFirstResponder()
}
return false
}
else{
if (textField.text?.characters.count)! > 1 {
let stringg = textField.text!
textField.text = stringg.replacingOccurrences(of: stringg, with: string)
}
let temptf = self.view.viewWithTag(next) as! UITextField
temptf.becomeFirstResponder()
}
}
}
return true
}
Swift 4
when you input a number from the pin code into a text field, you should let a number be shown and then the next text field will become the first responder, so change the first responder after the code was in the text view
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textField = textField as? PinCodeTextField else { return true }
if string == "" {// when the backward clicked, let it go :)
return true
}
// when textfield is not empty, well, next number
if textField.pinCode.count == textField.maxCount {
becomeFirstResponder(after: textField)
return false
}
if string.count > textField.maxCharacterCount {// the max character count should be 1
return false
}
return true
}
// now the text field has been filled with a number
func textFieldCotentDidChange(_ textField: UITextField) {
print("didchange")
guard let textField = textField as? PinCodeTextField else { return }
if textField.pinCode.count == 0 {
becomeFirstResponder(before: textField)
}
// when textfield has been filled, ok! next!
if textField.pinCode.count == textField.maxCharacterCount {
becomeFirstResponder(after: textField)
}
}
for more details and the simple demo, see this link
Try this
sample tutorial passcode lock
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UITextFieldDelegate>
{
IBOutlet UITextField *txtPassword;
}
#end
ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
txtPassword.delegate=self;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 1) ? NO : YES;
}
Just use TextFieldDelegate method and check the length of the TextField after every changes
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
if newString.characters.count == 1
{
nextTextField.becomeFirstResponder()
return true
}
else
{
return false
}
}
I was working on a similar functionality and did it in my way. Solution below.
Swift 4
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//For clear button pressed
//If the textfield has already text in it
if string.count == 0 {
textField.text = string
return true
}
//For First time entry into the text field
guard let text = textField.text, text.count <= 0 else {
//If user enter second character
return false
}
//For First time entry into the text field
if text.count == 0 {
textField.text = string
textField.resignFirstResponder()
self.nextResponde(tag: textField.tag)
return true
}
return false
}
//To make the next field as responder
func nextResponde(tag: Int) {
switch tag {
case self.PINTextField.tag:
guard let text = self.PINTextField1.text, text.count == 1 else {
self.PINTextField1.becomeFirstResponder()
return
}
case self.PINTextField1.tag:
guard let text = self.PINTextField2.text, text.count == 1 else {
self.PINTextField2.becomeFirstResponder()
return
}
case self.PINTextField2.tag:
guard let text = self.PINTextField3.text, text.count == 1 else {
self.PINTextField3.becomeFirstResponder()
return
}
default:
let _ = tag
}
}
Credit to #Anurag Soni, here's an alternate UX pushing onto the next field and dismissing upon completion (with layout logic also above):
-(UIView *)addSpacedTextInputToView:(UIView *)parent subtitle:(NSString *)subtitle spaces:(int)spaces atOffset:(float)offset{
float parentWidth = parent.frame.size.width;
float tfWidth = 2 * increment;
float tfHeight = 3 * increment;
float startX = 3 * increment;
float remainingWidth = parentWidth - 2 * startX - spaces * tfWidth;
float padding = remainingWidth / (float)(spaces-1);
UIView * holder = [self addViewToView:parent withFrame:CGRectMake(0, offset, parentWidth, 0)];
UIView * tfHolder = [self addViewToView:holder withFrame:CGRectMake(0, 0, parentWidth, tfHeight)];
float localX = startX;
float localY = 0.0f;
for (int n = 0; n < spaces; n++){
UITextField * tf = [UITextField new];
tf.frame = CGRectMake(localX, localY, tfWidth, tfHeight);
tf.textColor = [UIColor whiteColor];
tf.font = headerFont;
tf.textAlignment = NSTextAlignmentCenter;
tf.tintColor = [UIColor whiteColor];
tf.keyboardAppearance = UIKeyboardAppearanceDark;
tf.tag = n;
tf.delegate = self;
[tfHolder addSubview:tf];
UIView * div = [self addViewToView:tf withFrame:CGRectMake(0, tfHeight-2, tfWidth, 1)];
div.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.5f];
localX += tfWidth;
localX += padding;
}
localY += tfHeight;
localY += increment;
localY += [self addSystemLabelToView:holder colour:nil text:subtitle maxWidth:0 offset:localY].frame.size.height;
holder.frame = CGRectMake(0, offset, parent.frame.size.width, localY);
return holder;
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (string.length > 0){
textField.text = string.uppercaseString; //optional to uppercase
UIView * div = textField.subviews.firstObject; //change div colour
div.backgroundColor = [UIColor whiteColor];
int nextTag = (int)textField.tag + 1;
UIResponder * nextResponder = [textField.superview viewWithTag:nextTag];
if (!nextResponder){
[textField resignFirstResponder];
}
if (nextResponder){
[nextResponder becomeFirstResponder];
}
}
return false;
}
Objective-c answer of Varun Naharia solution.
Solution using IBOutletCollections
#property (strong, nonatomic) IBOutletCollection(UITextField) NSArray *otpTextFields;
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField.text.length < 1 && string.length > 0) {
for(int i=0; i<self.otpTextFields.count-1; i++) {
if(textField == self.otpTextFields[i]) {
UITextField* nextTextField = (UITextField*) self.otpTextFields[i+1];
[nextTextField becomeFirstResponder];
}
}
textField.text = string;
return NO;
} else if (textField.text.length >= 1 && string.length == 0) {
for(int i=(int) self.otpTextFields.count-1;i>=1;i--) {
if(textField == self.otpTextFields[i]) {
UITextField* nextTextField = (UITextField*) self.otpTextFields[i-1];
[nextTextField becomeFirstResponder];
}
}
textField.text = #"";
return NO;
} else if(textField.text.length >= 1){
textField.text = string;
return NO;
}
return YES;
}
try this : - For swift 3.0
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// On inputing value to textfield
if ((textField.text?.characters.count)! < 1 && string.characters.count > 0){
let nextTag = textField.tag + 1;
// get next responder
let nextResponder = textField.superview?.viewWithTag(nextTag);
textField.text = string;
if (nextResponder == nil){
textField.resignFirstResponder()
}
nextResponder?.becomeFirstResponder();
return false;
}
else if ((textField.text?.characters.count)! >= 1 && string.characters.count == 0){
// on deleting value from Textfield
let previousTag = textField.tag - 1;
// get next responder
var previousResponder = textField.superview?.viewWithTag(previousTag);
if (previousResponder == nil){
previousResponder = textField.superview?.viewWithTag(1);
}
textField.text = "";
previousResponder?.becomeFirstResponder();
return false;
}
return true;
}
converted Anurag Soni answer in swift 3.0
You just have to implement this method only.

Resources