I'm trying to limit 3 different textfields so that you can only enter numbers into them, and so that the number of digits you can enter is limited.
Here's my code:
import Foundation
import UIKit
import Darwin
class View3on3 : UIViewController, UITextFieldDelegate {
@IBOutlet weak var APTeams: UITextField!
@IBOutlet weak var APRounds: UITextField!
@IBOutlet weak var APBreakers: UITextField!
override func viewDidLoad()
{
super.viewDidLoad()
initializeTextFields()
}
func initializeTextFields()
{
APTeams.delegate = self
APTeams.keyboardType = UIKeyboardType.NumberPad
APRounds.delegate = self
APRounds.keyboardType = UIKeyboardType.NumberPad
APBreakers.delegate = self
APBreakers.keyboardType = UIKeyboardType.NumberPad
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
@IBAction func userTappedBackground(sender: AnyObject)
{
view.endEditing(true)
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
if string.characters.count == 0 {
return true
}
let prospectiveText = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: String())
switch textField {
case APTeams:
return prospectiveText.containsOnlyCharactersIn("0123456789") && count(prospectiveText) <= 3
case APRounds:
return prospectiveText.containsOnlyCharactersIn("0123456789") && count(prospectiveText) <= 1
case APBreakers:
return prospectiveText.containsOnlyCharactersIn("0123456789") && count(prospectiveText) <= 3
default:
return true
}
}
}
It throw an error at this line
let prospectiveText = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: String())
Saying that 'String?' is not convertible to NSString
I followed the tutorial at this site: http://www.globalnerdy.com/2015/04/27/how-to-program-an-ios-text-field-that-takes-only-numeric-input-or-specific-characters-with-a-maximum-length/
What am I doing wrong?
PS. The code to call a NumberPad is working fine. When I remove the code to limit the number of digits, it works fine. I'd also welcome any other improvements upon the code.