MY app crashes every time after I enter in a text to a text field. I am trying to get it to save after text has been entered and try to touch another textfield to edit but it just freezes. I am trying to use a textFieldDidEndEditing or EditingDidEnd for the text field. Any help would be much appreciated. Here is my statement.
//MARK: Text selected field delegate
extension ExerciseViewController: UITextFieldDelegate{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
var currentTextField = textFields[0]
if (currentTextField == textField) {
currentTextField = textFields[1]
currentTextField.becomeFirstResponder()
}
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
print("User is editing text field")
}
func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
let exercise = Exercise(context: context)
let client = Client(context: context)
exercise.reps = Int16(todayRepsTextField.text!)!
exercise.weight = Float(todayWeightTextField.text!)!
exercise.notes = todayNotesTextView.text
exercise.seat = Int16(seatPositionTextField.text!)!
exercise.nextWeight = Float(nextWeightTextField.text!)!
client.goals = goalsTextField.text
client.intensity = intensityTextField.text
client.medical = medicalTextField.text
client.notes = clientNotesTextField.text
exercise.exerciseInfo?.exerciseProtocol?.protocolName = protocolTextField.text
thisAppDelegate().saveContext()
}
}
Try not to use !
for casting it could crash the app. This is a quickfix to use optional values but isn't tested.
let exercise = Exercise(context: context)
exercise.reps = Int16(todayRepsTextField.text ?? "0") ?? 0
exercise.weight = Float(todayWeightTextField.text ?? "0") ?? 0
exercise.notes = todayNotesTextView.text
exercise.seat = Int16(seatPositionTextField.text ?? "0") ?? 0
exercise.nextWeight = Float(nextWeightTextField.text ?? "0") ?? 0
let client = Client(context: context)
client.goals = goalsTextField.text
client.intensity = intensityTextField.text
client.medical = medicalTextField.text
client.notes = clientNotesTextField.text
exercise.exerciseInfo?.exerciseProtocol?.protocolName = protocolTextField.text
thisAppDelegate().saveContext()