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?
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.
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.
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
}
}