swiftintappenduitextfielddelegatenscharacterset

append :00 to whatever is entered in the textfield


My code below restricts the user to only input 2 numbers into a textfield. All I want to do is append ':00' to whatever is entered into whatever is entered into the textfield. So if the user enters 30. The textfield should be 30:00. All code is listed below.

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

   @IBOutlet weak var txtMobileNumber: UITextField!

   let MAX_LENGTH_PHONENUMBER = 2
   let ACCEPTABLE_NUMBERS     = "0123456789"

   func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {                   
      let newLength: Int = textField.text!.count + string.count - range.length
      let numberOnly = NSCharacterSet.init(charactersIn: ACCEPTABLE_NUMBERS).inverted
      let strValid = string.rangeOfCharacter(from: numberOnly) == nil
      return (strValid && (newLength <= MAX_LENGTH_PHONENUMBER))
   }

   override func viewDidLoad() {
       super.viewDidLoad()
       // Do any additional setup after loading the view, typically from a nib.
       txtMobileNumber.delegate = self
   }
}

Solution

  • You need

        aTextField.addTarget(self, action: #selector(self.textFieldDidChange), for: UIControlEvents.editingChanged)        
    }
    
    @objc func textFieldDidChange(_ textField: UITextField) { 
       if  textField.text!.count == 2 {
          textField.text = textField.text! + ":00"
       }
    }