//
//  NumericUITextField.swift
//  ABC Bluetooth Demo
//
//  Created by AB Circle on 19/1/2021.
//  Copyright © 2020-2024 AB Circle. All rights reserved.
//

import Foundation
import UIKit

/// Class overriding a UITextField in order to enable numeric input only...
class NumericUITextField: UITextField, UITextFieldDelegate {
    
    /// :nodoc:
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        delegate = self
    }
    /// Tells the delegate when the user changes the text or attributes in the specified text field.
    /// Used here to fix the ". " back to double space
    ///
    /// - Parameter textField: The text field containing the changes.
    func editingChanged(_ textField: UITextField)
    {
        if let text = textField.text {
            textField.text = text.replacingOccurrences(of: ". ", with: "  ")
        }
    }
    
    /// Asks the delegate whether to replace the specified text in the text field.
    /// Used here to check if entered text conforms a characterset holding decimal values.
    ///
    /// - Parameters:
    ///   - textField: The text field containing the changes.
    ///   - range: The current selection range.
    ///   - text: The text to insert
    /// - Returns: True if the old text should be replaced by the new text; false if the replacement operation should be aborted.
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let allowedCharacters = CharacterSet(charactersIn:"0123456789")//Here change this characters based on your requirement
        let characterSet = CharacterSet(charactersIn: string)

        return allowedCharacters.isSuperset(of: characterSet)
    }
}



