First, be sure that your view controller conforms to the UITextFieldDelegate protocol:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
// Your different code
override func viewDidLoad() {
tremendous.viewDidLoad()
// Assuming you may have a UITextField named textField
textField.delegate = self
}
// Your different code
}
Then, implement the textField(_:shouldChangeCharactersIn:replacementString:) methodology so as to add areas each 4 characters:
swift
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
tremendous.viewDidLoad()
textField.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn vary: NSRange, replacementString string: String) -> Bool {
// Take away any areas from the present textual content
let textWithoutSpaces = textField.textual content?.replacingOccurrences(of: " ", with: "") ?? ""
// Mix the brand new string with the prevailing textual content with out areas
let newText = (textWithoutSpaces as NSString).replacingCharacters(in: vary, with: string)
// Insert areas each 4 characters
let formattedText = newText.chunkFormatted(withChunkSize: 4, separator: " ")
// Replace the textual content discipline's textual content
textField.textual content = formattedText
// Because you're updating the textual content manually, return false to stop default conduct
return false
}
}
extension String {
func chunkFormatted(withChunkSize chunkSize: Int, separator: String) -> String {
return stride(from: 0, to: depend, by: chunkSize).map {
let begin = index(startIndex, offsetBy: $0)
let finish = index(begin, offsetBy: chunkSize, limitedBy: endIndex) ?? endIndex
return String(self[start..<end])
}.joined(separator: separator)
}
}