如何在iOS8的Swift中限制UITextField中的1个小数位? [英] How do you limit only 1 decimal entry in a UITextField in Swift for iOS8?

查看:153
本文介绍了如何在iOS8的Swift中限制UITextField中的1个小数位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经到处搜索了,但是似乎仍然无法正常工作.我有一个带有UITextField的简单iOS程序,该程序将Farenheit转换为Celsius和Kelvin.我试图在此UITextField中仅限制1个十进制输入.例如98.9可以,但98..9不能.

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.

这是我只想限制1个小数的函数.我想输入的是小数点后1位,则不允许再输入1个,但是当然可以在第一个小数点后输入数字.

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
        }
      }

推荐答案

您可以设置UITextField.delegate = self并使用textField(textField: UITextField,shouldChangeCharactersInRange range: NSRange,replacementString string: String)方法执行所需的操作.

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.

以下代码不允许您在文本字段中输入 1个小数点.

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
}

这篇关于如何在iOS8的Swift中限制UITextField中的1个小数位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆