When you post code, don't post in comments. It is totally messed up.
Here it is formatted:
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var benchPressPB: UITextField!
@IBOutlet weak var squatPB: UITextField!
@IBOutlet weak var deadliftPB: UITextField!
@IBOutlet weak var ohpPB: UITextField!
@IBOutlet weak var rackPullPB: UITextField!
@IBOutlet weak var legPressPB: UITextField!
@IBOutlet weak var pullUpsPB: UITextField!
var textFields = var textFieldKeys = [ "benchPressPB", "squatPB", "deadliftPB", "ohpPB", "rackPullPB", "legPressPB", "pullUpsPB" ]
var textFieldStrings =
override func viewDidLoad() {
super.viewDidLoad()
self.benchPressPB.delegate = self
self.squatPB.delegate = self
self.deadliftPB.delegate = self
self.ohpPB.delegate = self
self.rackPullPB.delegate = self
self.legPressPB.delegate = self
self.pullUpsPB.delegate = self
textFields = [benchPressPB, squatPB, deadliftPB, ohpPB, rackPullPB, legPressPB, pullUpsPB]
for (index, key) in textFieldKeys.enumerated() {
let aValue = UserDefaults.standard.string(forKey: key)
textFields[index].text = aValue
textFieldStrings.append(aValue ?? "")
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
let newText = textField.text
if let index = textFields.firstIndex(of: textField) {
textFieldStrings[index] = newText
UserDefaults.standard.set(newText, forKey: textFieldKeys[index])
}
return true
}
}
// My full code for my app, to provide a new default value, do I first need to declare it as a variable? or am I completely missing the point. Apologies if this is a completely dumb question. I am literally brand new to this and was advised the best way to learn was to just build something instead of a boring udemy course. I had to delete some of the code to post... UITextFields() & UIString() Really appreciate all your help!
There is something that doesn't mean anything:
var textFields = var textFieldKeys = [ "benchPressPB", "squatPB", "deadliftPB", "ohpPB", "rackPullPB", "legPressPB", "pullUpsPB" ]
var textFieldStrings =
The error here:
if let index = textFields.firstIndex(of: textField) {
textFieldStrings[index] = newText
UserDefaults.standard.set(newText, forKey: textFieldKeys[index])
}
textField is UITextField ;
textFields is an array of String (I assume)
So you should search for newText. But it is an optional, you need to unwrap first
if let newText = textField.text, let index = textFields.firstIndex(of: newText) {