Here is my code:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var maximumNumber: UITextField!
@IBAction func playButtonPressed(_ sender: Any) {
maximumNumber.isHidden = true
guessTextField.isHidden = false
}
@IBOutlet weak var guessTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
guessTextField.isHidden = true
maximumNumber.keyboardType = .numberPad
guessTextField.keyboardType = .numberPad
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
// Create an `NSCharacterSet` set which includes everything *but* the digits
let inverseSet = NSCharacterSet(charactersIn:"0123456789").inverted
// At every character in this "inverseSet" contained in the string,
// split the string up into components which exclude the characters
// in this inverse set
let components = string.components(separatedBy: inverseSet)
// Rejoin these components
let filtered = components.joined(separator: "") // use join("", components) if you are using Swift 1.2
// If the original string is equal to the filtered string, i.e. if no
// inverse characters were present to be eliminated, the input is valid
// and the statement returns true; else it returns false
return string == filtered
}
}
}
I want the text fields maximumNumber and guessTextField allow only integers. I've tried using other functions and delegates I've found here, but they fail to work or I get compiler errors.