I've been wanting to code for a while, and just started using my free time to try to learn so I know very little but am eager to learn! Also first time poster. I'm making a simple dice game app, and I've been horribly stuck trying to unwrap strings and variables. I keep getting the error "Unexpectedly found nil while implicitly unwrapping an Optional value" when trying to assign a user input name to a label on the next view controller.
Let me know if this is too convoluted off an app design, but this is what I'm trying to design: first view controller where 2-4 players enter their names. They hit the next button and it takes them to the next viewController where there are dice, a roll button, and the names they just entered.
I have the UITextField and UILabel for the names correctly connected to IBOutlets. I forced the UITextField to unwrap by making them optional to prevent the app from crashing, but the names are still not updated. Here's my code:
class ViewController: UIViewController, UITextViewDelegate, UITextFieldDelegate {
@IBOutlet weak var name1: UITextField!
@IBOutlet weak var name2: UITextField!
@IBOutlet weak var name3: UITextField!
@IBOutlet weak var name4: UITextField!
//connects name strings
@IBOutlet weak var dice1: UIImageView!
@IBOutlet weak var dice2: UIImageView!
@IBOutlet weak var dice3: UIImageView!
@IBOutlet weak var dice4: UIImageView!
//links dice images
@IBOutlet weak var name1Label: UILabel!
@IBOutlet weak var name3Label: UILabel!
@IBOutlet weak var name4Label: UILabel!
@IBOutlet weak var name2Label: UILabel!
//links name labels on second viewController
var diceArray = ["dice1", "dice2", "dice3", "dice4", "dice5", "dice6"]
//creates an array to set dice images
var randomArray = [0,0,0]
var randomDice1 : Int = 0
var randomDice2 : Int = 0
var randomDice3 : Int = 0
//creates variables to hold random number
func storeNames () {
name1Label?.text = name1.text. THIS IS WHERE I KEEP GETTING FATAL ERRORS
name2Label?.text = name2.text
name3Label?.text = name3.text
name4Label?.text = name4.text
//stores the user inputed names into an array
}
//stores the names from textfield into name strings
override func viewDidLoad() {
super.viewDidLoad()
Thread.sleep(forTimeInterval:0.25)
//extends loading screen
name1?.placeholder = "Player 1 Name"
name2?.placeholder = "Player 2 Name"
name3?.placeholder = "Player 3 Name"
name4?.placeholder = "Player 4 Name"
//Creates placeholder text
let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing))
view.addGestureRecognizer(tap)
//removes keyboard when you tap outside keyboard
}
@IBAction func nextButton(_ sender: UIButton) {
storeNames()
}