0

So my question is about making a text filter in Swift for iOS. The idea is about making an alert such that if the user has inputed a string it would alert the user to input only numbers, because the program is a calculator. So where in this filter do I need to put the alert code?

class ViewController: NSObject, UITextFieldDelegate {

    func TextField(TextField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        var result = true
        if countElements(string) > 0 {
            let numericInput = NSCharacterSet(charactersInString: "0123456789.-").invertedSet
            if let badRange = string.rangeOfCharacterFromSet(numericInput) {
                let substring = string.substringToIndex(badRange.startIndex)
                let oldString: NSString = TextField.text // necessary so we can use the NSRange object passed in.
                TextField.text = oldString.stringByReplacingCharactersInRange(range, withString: substring)

                result = false

            }
        }
        return false
    }
}
Lyndsey Scott
  • 37,080
  • 10
  • 92
  • 128
Santis
  • 115
  • 1
  • 1
  • 5
  • Put the alert code within your `if let badRange` block. But also make sure you're returning "result" and not "false" at the end. – Lyndsey Scott Dec 20 '14 at 22:43
  • 2
    I guess you have a typo in your code and it should be lower case `textField`? – qwerty_so Dec 20 '14 at 22:46
  • Also, from a usability point of view. re-think the alert, unless this is just something you are doing to learn how to use alerts. It is better to ignore the invalid keystrokes than to pop a modal alert that requires user action to dismiss – Paulw11 Dec 20 '14 at 22:58

1 Answers1

-3

There is no reason for displaying an alert for something as trivial as only allowing numerical input.

For what you are trying to do, simply choose an appropriate keyboardType.

This has been answered here and is easily found in the documentation.

Community
  • 1
  • 1
David Ganster
  • 1,985
  • 1
  • 18
  • 26
  • 1
    This isn't an appropriate answer for the OP's question in this case because the purpose of his code within that if block seems specifically to allow for the copying and pasting of text... As in it keeps all numerical characters before a non-numerical character is found, thus handling replacement strings of multiple characters. Copied and pasted text can still contain non-numerical characters even with a number only keyboard type. – Lyndsey Scott Dec 20 '14 at 22:55
  • Even so, there is no reason to display an alert. The OPs code should already work fine (save for the typos and wrong return value that you mentioned) for just filtering the text. – David Ganster Dec 20 '14 at 23:01
  • This answer is only referring to an answer that doesn't really answer the question. Setting the keyboard type doesn't filter user's input when pasting. – Adro Jan 07 '21 at 10:50