Kalpesh
Kalpesh

Reputation: 75

How to restrict textfield to accept only decimal values in swift

I want to accept only decimal values in my textfield.

The following code allows me to enter only numbers and '.' but we can enter more than one '.'

How can i restrict it to just one '.' or how can I restrict the textfield to accept only decimal values in swift 3.1

let aSet = NSCharacterSet(charactersIn:"0123456789.").inverted
let compSepByCharInSet = r_Qty_txt.text?.components(separatedBy: aSet)
let numberFiltered = compSepByCharInSet?.joined(separator: "")

My target device is iPad.

listViewCell.swift Code

import UIKit

class listViewCell: UITableViewCell, UITextFieldDelegate {

var delegate: CellInfoDelegate?

@IBOutlet weak var desc_lbl: UILabel!
@IBOutlet weak var openQty_lbl: UILabel!
@IBOutlet weak var r_Qty_txt: UITextField!
@IBOutlet weak var itemId_lbl: UILabel!

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let newString: String = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    let expression: String = "^[0-9]*((\\.|,)[0-9]{0,2})?$"
    //var error: Error? = nil
    let regex = try? NSRegularExpression(pattern: expression, options: .caseInsensitive)
    let numberOfMatches: Int = (regex?.numberOfMatches(in: newString, options: [], range: NSRange(location: 0, length: (newString.characters.count ))))!
    return numberOfMatches != 0
}


public func configure(textVal: String?, placeholder: String){
    r_Qty_txt.text = textVal
    r_Qty_txt.placeholder = placeholder

    r_Qty_txt.accessibilityValue = textVal
    r_Qty_txt.accessibilityLabel = placeholder

}

@IBAction func QtyEntered(_ sender: UITextField) {
    print("Value Added \(String(describing: r_Qty_txt.text)) and \(String(describing: openQty_lbl.text))")
    if (r_Qty_txt.text!.isEmpty) {

    }else if(Int(r_Qty_txt.text!)! > Int(openQty_lbl.text!)!){
        print("Not Allowed")
        r_Qty_txt.text = nil
    }
}

override func awakeFromNib() {
    r_Qty_txt.delegate = self
    super.awakeFromNib()
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}
}

Upvotes: 0

Views: 4177

Answers (2)

Nirav D
Nirav D

Reputation: 72410

If you want to allow just decimal number with your textField you can simply make it like this way no need to compare anything else.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField.text != "" || string != "" {
        let res = (textField.text ?? "") + string
        return Double(res) != nil
    }
    return true
}

Upvotes: 6

elk_cloner
elk_cloner

Reputation: 2149

select keyboard type just like this from atribute inspector for only numbers.

try this delegate for only one dots

and use delegate for only one decimal points(.)

func textField(textField: UITextField,shouldChangeCharactersInRange range: NSRange,replacementString string: String) -> Bool
{
    let countdots = textField.text.componentsSeparatedByString(".").count - 1

    if countdots > 0 && string == "."
    {
        return false
    }
    return true
}

Upvotes: 1

Related Questions