0

I am using the Xcode 7 beta 5 and Swift 2. I currently have a UITextField and a UIButton. The UITextField is set to a decimal pad, but however, the user is able to enter in multiple decimals. That is not how I would like the app to work. I would like to check, when the button is tapped, if the text field has 0-1 decimal points. Is there any statement that checks for multiple decimal points?

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Pranav Wadhwa
  • 7,666
  • 6
  • 39
  • 61

2 Answers2

3

Give the text field a delegate and implement textField:shouldChangeCharactersInRange:replacementString: to prevent the user from entering a decimal point if there is already one present.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Sorry, but that didn't really work for me. Could you please try to be more specific? I tried entering in both pieces of code, but they didn't work... – Pranav Wadhwa Aug 16 '15 at 00:58
3

Replace textField with a reference to your UITextField in this:

   if textField.text.componentsSeperatedByString(".").count >= 3 {
          // more than 1 decimal point
    }

This seperates the text in the text field into an array and creates an array of strings separated on any decimal points. If there are 0-1 decimal points, the array will have less than 3 items. This documentation might be helpful.

ezig
  • 1,219
  • 1
  • 10
  • 15