Pranav Wadhwa
Pranav Wadhwa

Reputation: 7746

If string contains statement - Swift 2 Xcode 7

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?

Upvotes: 0

Views: 289

Answers (2)

ezig
ezig

Reputation: 1229

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.

Upvotes: 3

matt
matt

Reputation: 536057

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.

Upvotes: 3

Related Questions