Search code examples
iosif-statementcontainsswift2xcode7-beta5

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?


Solution

  • 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.