I am new to Swift, I am currently reading the Big Nerd Ranch book to understand more. I have an application that allows the user to type the temperature in Fahrenheit then will be converted to Celsius and displayed on the interface. The application only displays one fractional digit on the Celsius label. Now I want to disallow the user from entering the alphabetic characters. I have been trying to figure out how to do so but I wasn't able to get the idea. Any help would be much appreciated. Here is my code so far:
import UIKit
class ConversionViewController : UIViewController , UITextFieldDelegate {
@IBOutlet var textField: UITextField!
@IBOutlet var celsiusLabel: UILabel!
var fahrenheitValue: Measurement<UnitTemperature>?
{
didSet {
updateCelsiusLabel()
}
}
var celsiusValue: Measurement<UnitTemperature>? {
if let fahrenheitValue = fahrenheitValue {
return fahrenheitValue.converted(to: .celsius)
} else {
return nil
}
}
func updateCelsiusLabel() {
if let celsiusValue = celsiusValue {
celsiusLabel.text = numberFormatter.string(from: NSNumber(value: celsiusValue.value))
} else {
celsiusLabel.text = "???"
}
}
let numberFormatter: NumberFormatter = {
let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.minimumFractionDigits = 0
nf.maximumFractionDigits = 1
return nf
}()
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool {
let existingTextHasDecimalSeparator = textField.text?.range(of: ".")
let replacementTextHasDecimalSeparator = string.range(of: ".")
if existingTextHasDecimalSeparator != nil,
replacementTextHasDecimalSeparator != nil {
return false
} else {
return true
}
}
@IBAction func fahrenheitFieldEditingChanged(_ textField: UITextField) {
if let text = textField.text, let value = Double(text) {
fahrenheitValue = Measurement(value: value, unit: .fahrenheit)
} else {
fahrenheitValue = nil
}
}
@IBAction func dismissKeyboard(_ sender: UITapGestureRecognizer) {
textField.resignFirstResponder()
}
override func viewDidLoad() {
super.viewDidLoad()
updateCelsiusLabel()
}
}