How can I declare that a text field can only contain an integer?

前端 未结 9 1881
星月不相逢
星月不相逢 2020-11-30 05:37

In swift, I am trying to make a text field that will allow a button to be enabled, but only when the text field contains an integer. How can I do this?

相关标签:
9条回答
  • 2020-11-30 06:31

    Each text field has a keyboardType. You could set this to UIKeyboardType.NumbersAndPunctuation to only show numbers and still have the return key present (defensive UI). You could then use NSScanner's scanInt() to check if textField.text is a valid integer.

    0 讨论(0)
  • 2020-11-30 06:31

    You can use NSScanner to do that here is the which might be useful trying using this and let me know if there are any issues

    if( [[NSScanner scannerWithString:@"-123.4e5"] scanFloat:NULL] )
        NSLog( @"\"-123.4e5\" is numeric" );
    else
        NSLog( @"\"-123.4e5\" is not numeric" );
    
    if( [[NSScanner scannerWithString:@"Not a number"] scanFloat:NULL] )
        NSLog( @"\"Not a number\" is numeric" );
    else
        NSLog( @"\"Not a number\" is not numeric" );
    

    go through the link http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Objective-C. Try it in swift the class and method names are same.

    0 讨论(0)
  • 2020-11-30 06:35

    1st you have to inherit the UITextViewDelegate class with you own class

    class ViewController: UIViewController, UITextViewDelegate {
    

    2nd add an IBOutlet

    @IBOutlet weak var firstName: UITextField!
    

    3rd you have to assure this object is using

    override func viewDidLoad() {
            super.viewDidLoad()
       firstName.delegate = self
    }
    
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField == firstName {
                    let allowedCharacters = "1234567890"
                    let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
                    let typedCharacterSet = CharacterSet(charactersIn: string)
                    let alphabet = allowedCharacterSet.isSuperset(of: typedCharacterSet)
                  return alphabet
    
    
    
          }
      }
    
    0 讨论(0)
提交回复
热议问题