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
}
}
You can use this subclass of UITextField. It uses the same principle as the answers above, but with a little bit clearer code.
Swift 3
You can set the
UITextField.delegate = self
and use thetextField(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.
You should add
UITextFieldDelegate
toclass ViewController
:then
If name of your
@IBOutlet
istextField
, (it could looks like:@IBOutlet weak var textField: UITextField!
), then addafter that you could use:
Swift 4: This works !
I used below code to limit 1 decimal entry in swift 3.0.