1

(Swift) So the problem is:

My app (which is a kind of calculator) is crashing when the user puts in the textfield things that can't be calculated.

For example, if he types " -4-.", the app won't be able to do the math. So, a pattern must be followed.

The following characters are allowed: 1234567890.-

The minus sign can only be typed when it is the first character in the textfield and cannot be typed again. The point can only be typed after a number, and cannot be typed again.

Caio Gomes
  • 139
  • 11
  • that means you don't want any non-numeric characters(+,/,-,*) at the end of textfield while hitting calculate button.. so that you can perform the math right..? – Gokul G Jul 28 '16 at 09:56
  • Not only at the end, but also only special characters. It needs to be a valid decimal. @Gokul – Caio Gomes Jul 28 '16 at 10:46
  • **FYI** i have added my answer below,Check it out and let me know if it satisfies your question. – Gokul G Jul 28 '16 at 11:58

2 Answers2

0

Well you would have to determine:

When the user clicks on a number/digit/character, you would have to do a:

//Goes at top of one of your classes
var decimalCount:Int = 0

//At location of tap for character
if(decimalCount < 1) {
    textField.text += "."
    decimalCount += 1
}

This ideology could be applied to "-" as well.

impression7vx
  • 1,728
  • 1
  • 20
  • 50
  • But this would work for the kind of calculator that you need to press uibuttons for numbers, wouldn't it? My app opens the keyboard for, will it work too? (sorry for the noobness) – Caio Gomes Jul 25 '16 at 00:43
  • Ahh! I figured you were either using uibuttons or the NumPad keyboard. Hmm – impression7vx Jul 25 '16 at 01:27
  • Question. Why use the entire keyboard when you can only use a select few characters? – impression7vx Jul 25 '16 at 01:58
  • I need a keyboard that has "-" and "." (and, of course, the numbers). I set a range of characters, so only numbers and these 2 can be typed in. (note: I just solved the "-" problem. As it can only be the 1st, if the numbers of characters are above 0, the range changes. I will try to do this for ".", but will be complex, as we can have 1.2 and 199999.9999) – Caio Gomes Jul 25 '16 at 02:01
  • Hmm. I would reccommend a custom keyboard or using numpad. Idk what the numpad keyboard has on it (Apple gives us a default numpad keyboard). Also http://code.tutsplus.com/tutorials/ios-8-creating-a-custom-keyboard-in-swift--cms-22344 for custom keybord – impression7vx Jul 25 '16 at 02:03
  • But even tough I use a custom keyboard with only the characters that I need, I would still have the same problem: preventing a bored user to crash the app putting a lot of points in the number. – Caio Gomes Jul 25 '16 at 02:08
  • http://stackoverflow.com/questions/26566844/limiting-user-input-to-a-valid-decimal-number-in-swift – impression7vx Jul 25 '16 at 02:10
0

Some how i have understood your question. According to my assumption our task is to validate the input for proper math function.Ok here we go.

  1. First of all declare a bool variable at top of your class

    var isNonNumericCharactersAllowes = true
    
  2. At first we need to make our textfield to respond according to user input.So add delegate to text field and add the following delegate method.

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    
    //1. To make sure that this is applicable to only particular textfield add tag.
    if textField.tag == 1 {
        let  char = string.cStringUsingEncoding(NSUTF8StringEncoding)!
        let isBackSpace = strcmp(char, "\\b")
        //Helps to react only while typing and not while clearing text
        if (isBackSpace != -92) {
            let numbersOnly = NSCharacterSet(charactersInString: "1234567890")
            let characterSetFromTextField = NSCharacterSet(charactersInString: string)
            let Validate:Bool = numbersOnly .isSupersetOfSet(characterSetFromTextField)
    
            if !Validate {
                if isNonNumericCharactersAllowes {
                    isNonNumericCharactersAllowes = false
                    return true
                }
                return false
            }
            isNonNumericCharactersAllowes = true
    
        }
    
      }
      return true
    }
    
  3. The above method stops unusual text entry's such as 0..012,--4,4++ etc..

  4. Now while hitting calculate button we need to some validation.Add the following code in IBAction.

    @IBAction func calculate(sender: AnyObject) {
      let textContent:String!
      textContent = textFieldTwo.text
    
      var characterContainer = textContent.characters.map { String($0) }
      let numbersOnly = NSCharacterSet(charactersInString: "1234567890")
      let lastObjectOfString = NSCharacterSet(charactersInString: characterContainer.last!)
      let Validate:Bool = numbersOnly .isSupersetOfSet(lastObjectOfString)
      if !Validate {
          characterContainer .removeLast()
          textFieldTwo.text = characterContainer .joinWithSeparator("")
      }
     }
    
    1. This above validation helps in removing things like 30+20+,4+4+, etc.. i.e removes unused operators at the end.
Gokul G
  • 2,046
  • 15
  • 22