数字输入在文本字段中

时间:2021-06-21 20:29:14

Additional question:

Still need some help with my code. The textfield is 'measuredValue' and I plan to have 30 different texfields (measuredValue1...30). When I type '923' the text will be set to '9.23' right away. Then I want to add '4'... for '92.34' but that doesn't work. Thanks for helping out.

我的代码仍需要一些帮助。文本字段是'measuredValue',我计划有30个不同的texfields(measuredValue1 ... 30)。当我输入'923'时,文本将立即设置为'9.23'。然后我想为'92 .34'添加'4'...但这不起作用。谢谢你的帮助。

func textField(textField: UITextField,
shouldChangeCharactersInRange range: NSRange,
replacementString string: String)
-> Bool {

    if count(string) == 0 { return true }

    var measuredValue = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)

    switch textField {

    case digitsOnlyTextField:

        if count(measuredValue) == 3  || count(measuredValue) == 4 {
            let stringNumeric = Double(measuredValue.toInt()!) / 100
            measuredValue = String(format:"%.2f", stringNumeric)
            digitsOnlyTextField.text = measuredValue
        }

        return measuredValue.containsOnlyCharactersIn("0123456789") && count(measuredValue) <= 4

    default:
        return true
    }

}

Original question:

I would like to validate my text fields to get the right input for my app. Input needs to be formatted like '9.90' or '15.34'. So always 3 or 4 digits, and always 2 decimals.

我想验证我的文本字段以获得我的应用程序的正确输入。输入需要格式化为'9.90'或'15 .34'。所以总是3或4位数,总是2位小数。

I would like to use 'numberpad keyboard' (just 0...9, no point) and add the decimal point after the user exits the field. So the user input is 990 or 1534, and then in the text field it will become 9.90 or 15.34 automatically.

我想使用'numberpad keyboard'(只有0 ... 9,没有点)并在用户退出该字段后添加小数点。因此用户输入为990或1534,然后在文本字段中自动变为9.90或15.34。

I tried searching for examples first, but didn't find what I was looking for. Any help appreciated. Jan

我首先尝试搜索示例,但没找到我要找的东西。任何帮助赞赏。一月

2 个解决方案

#1


You have to implement the UITextField delegate method

您必须实现UITextField委托方法

func textFieldDidEndEditing(textField: UITextField) {
    //Logic goes here....
    var textString = textField.text as! String
    let textLength = countElements(textString)
    if textLength >= 3 && textLength <= 4 {
        let stringNumeric = Double(textString.toInt()!) / 100
        let texts = String(format:"%.2f", stringNumeric)
        textField.text = texts
    }
}

Your class should confirm to the protocol UITextFieldDelegate

您的类应该确认协议UITextFieldDelegate

#2


this is the 'final' code I used (but I'm open for improvements!). A few remarks:

这是我使用的“最终”代码(但我愿意改进!)。几点评论:

  1. when a user clicks the background (and leaves the textfield) the decimal point gets set.
  2. 当用户单击背景(并离开文本字段)时,小数点被设置。

  3. when a user copies & pastes text from another app, this code handles that.
  4. 当用户从另一个应用程序复制并粘贴文本时,此代码会处理该文本。

  5. when a user goes back in the textfield for editing, the decimal point gets set again.
  6. 当用户返回文本域进行编辑时,会再次设置小数点。

  7. Deleting a value (to an empty textfield) is handled correctly.
  8. 正确处理删除值(到空文本字段)。

So I'm pleased. Thanks for the help.

所以我很高兴。谢谢您的帮助。

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var numberField: UITextField!

  override func viewDidLoad() {
super.viewDidLoad()
numberField.delegate = self
numberField.keyboardType = UIKeyboardType.NumberPad
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

// Tap background to add decimal point and defocus keyboard

@IBAction func userTappedBackground(sender: AnyObject) {
for view in self.view.subviews as! [UIView] {
  if let textField = view as? UITextField {
    if count(numberField.text) > 0 {
        var numberString = numberField.text
        numberString = numberString.stringByReplacingOccurrencesOfString(".", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
        var numberFromString = Double(numberString.toInt()!) / 100
        numberField.text = String(format:"%.2f", numberFromString)
    }
    textField.resignFirstResponder()
  }
}
}

func textField(textField: UITextField,
    shouldChangeCharactersInRange range: NSRange,
    replacementString string: String)
    -> Bool {
        var result = true
        var prospectiveText = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
        prospectiveText = prospectiveText.stringByReplacingOccurrencesOfString(".", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
        if textField == numberField {
            if count(string)>0 {
                let disallowedCharacterSet = NSCharacterSet(charactersInString: "0123456789").invertedSet
                let replacementStringIsLegal = string.rangeOfCharacterFromSet(disallowedCharacterSet) == nil
                 let resultingStringLengthIsLegal = count(prospectiveText) <= 4
                let scanner = NSScanner(string: prospectiveText)
                let resultingTextIsNumeric = scanner.scanDecimal(nil) && scanner.atEnd
                result = replacementStringIsLegal && resultingStringLengthIsLegal && resultingTextIsNumeric
            }
        }
        return result
}

#1


You have to implement the UITextField delegate method

您必须实现UITextField委托方法

func textFieldDidEndEditing(textField: UITextField) {
    //Logic goes here....
    var textString = textField.text as! String
    let textLength = countElements(textString)
    if textLength >= 3 && textLength <= 4 {
        let stringNumeric = Double(textString.toInt()!) / 100
        let texts = String(format:"%.2f", stringNumeric)
        textField.text = texts
    }
}

Your class should confirm to the protocol UITextFieldDelegate

您的类应该确认协议UITextFieldDelegate

#2


this is the 'final' code I used (but I'm open for improvements!). A few remarks:

这是我使用的“最终”代码(但我愿意改进!)。几点评论:

  1. when a user clicks the background (and leaves the textfield) the decimal point gets set.
  2. 当用户单击背景(并离开文本字段)时,小数点被设置。

  3. when a user copies & pastes text from another app, this code handles that.
  4. 当用户从另一个应用程序复制并粘贴文本时,此代码会处理该文本。

  5. when a user goes back in the textfield for editing, the decimal point gets set again.
  6. 当用户返回文本域进行编辑时,会再次设置小数点。

  7. Deleting a value (to an empty textfield) is handled correctly.
  8. 正确处理删除值(到空文本字段)。

So I'm pleased. Thanks for the help.

所以我很高兴。谢谢您的帮助。

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var numberField: UITextField!

  override func viewDidLoad() {
super.viewDidLoad()
numberField.delegate = self
numberField.keyboardType = UIKeyboardType.NumberPad
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

// Tap background to add decimal point and defocus keyboard

@IBAction func userTappedBackground(sender: AnyObject) {
for view in self.view.subviews as! [UIView] {
  if let textField = view as? UITextField {
    if count(numberField.text) > 0 {
        var numberString = numberField.text
        numberString = numberString.stringByReplacingOccurrencesOfString(".", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
        var numberFromString = Double(numberString.toInt()!) / 100
        numberField.text = String(format:"%.2f", numberFromString)
    }
    textField.resignFirstResponder()
  }
}
}

func textField(textField: UITextField,
    shouldChangeCharactersInRange range: NSRange,
    replacementString string: String)
    -> Bool {
        var result = true
        var prospectiveText = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
        prospectiveText = prospectiveText.stringByReplacingOccurrencesOfString(".", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
        if textField == numberField {
            if count(string)>0 {
                let disallowedCharacterSet = NSCharacterSet(charactersInString: "0123456789").invertedSet
                let replacementStringIsLegal = string.rangeOfCharacterFromSet(disallowedCharacterSet) == nil
                 let resultingStringLengthIsLegal = count(prospectiveText) <= 4
                let scanner = NSScanner(string: prospectiveText)
                let resultingTextIsNumeric = scanner.scanDecimal(nil) && scanner.atEnd
                result = replacementStringIsLegal && resultingStringLengthIsLegal && resultingTextIsNumeric
            }
        }
        return result
}