0

I'm using this piece of code to limit user input regarding the keyboard.

 func textField(_ textField: UITextField, shouldChangeCharactersIn     range: NSRange, replacementString string: String) -> Bool {
    let allowedCharacters = CharacterSet.init(charactersIn: ".0123456789")
    let characterSet = NSCharacterSet(charactersIn: string)

    return allowedCharacters.isSuperset(of: characterSet as CharacterSet)
}

but my program crashes when I enter any character. enter image description here

Update 2: So 99.9% of this solution works great, unfortunately the period/decimal point does not register. Unsure why this is happening?

Jon Gi
  • 39
  • 1
  • 8

1 Answers1

0

This appears to be a bug in Swift, there are multiple issues on this matter on the Swift issue tracker: https://bugs.swift.org/browse/SR-3311, https://bugs.swift.org/browse/SR-3667

Until this has been fixed, you can workaround this problem by using the following extension:

extension CharacterSet {

    func isSupersetOf(other: CharacterSet) -> Bool {
        return CFCharacterSetIsSupersetOfSet(self as CFCharacterSet, (other as NSCharacterSet).copy() as! CFCharacterSet)
    }
}

Keep in mind that you need to change your characterSet variable from type NSCharacterSet to CharacterSet to be able to use that extension in your example.

b_ray
  • 696
  • 6
  • 10
  • Excuse the ignorance as i've never used extensions before. is this placed below viewDidLoad? – Jon Gi Jun 23 '17 at 20:41
  • `viewDidLoad` is a method on `UIViewController`, you can not define an extension on that level - no. – b_ray Jun 23 '17 at 20:43
  • I made a new file by itself. However, now I'm able to enter any character into my text field. – Jon Gi Jun 23 '17 at 20:44
  • No, you need to put the extension outside of you class - above the opening statement `class ClassName {`, below the closing bracket of the `class`, or even in an own file, as you see fit. – b_ray Jun 23 '17 at 20:47