esx0001 esx0001 - 3 months ago 18
iOS Question

How do you limit only 1 decimal entry in a UITextField in Swift for iOS8?

I have searched all around for this but still cannot seem to get it to work. I have a simple iOS program with a UITextField that converts Farenheit to Celsius and Kelvin. I am trying to limit only 1 decimal entry in this UITextField. For example 98.9 is ok but 98..9 is not.

This is the function in which I want to limit only 1 decimal. What I would like is if 1 decimal is entered then it will not allow another 1 to be entered but numbers can still be entered after the first decimal of course.

func farenheitButton(sender: AnyObject)
{
var fVal = self.farenheitTextLabel.text
var cVal = self.celsiusTextLabel.text
var kVal = self.kelvinTextLabel.text

if let fVal = self.farenheitTextLabel.text?.toDouble()
{
var fValx = self.farenheitTextLabel.text
var fDoubleValue : Double = NSString (string: fValx).doubleValue

var fToC = (fDoubleValue - 32) * (5/9) //convert Farenheit to Celsius formula
var fToK = ((fDoubleValue - 32) / (1.8000)) + 273.15 //convert Farenheit to Kelvin formula

//create string from value with a format
var afToC : Double = fToC
var bfToC : String = String(format:"%.4f",afToC)

var afToK : Double = fToK
var bfToK : String = String(format:"%.4f",afToK)

celsiusTextLabel.text = bfToC
kelvinTextLabel.text = bfToK
}
}

Answer

You can set the UITextField.delegate = self and use the textField(textField: UITextField,shouldChangeCharactersInRange range: NSRange,replacementString string: String) method to do what you want.

The following code will not allow you to enter more than 1 decimal point in the textfield.

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
}