Get data writing in UITextField - swift

I am creating a form for taking measurements and I therefore have several text files. I need to be able to retrieve what the user writes in the textField. I tried several methods but I can't find a way to get there. Can you give me a lead?
Here is my code:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
var myTextField = UITextField()
#IBOutlet weak var wristFlex: UITextField!
#IBOutlet weak var wristExtension: UITextField!
#IBOutlet weak var firstPhalanx: UITextField!
#IBOutlet weak var secondPhalanx: UITextField!
#IBOutlet weak var thirdPhalanx: UITextField!
#IBOutlet weak var forearmLenght: UITextField!
#IBOutlet weak var handLenght: UITextField!
#IBOutlet weak var fingerLenght: UITextField!
#IBOutlet weak var forearmCirecumference: UITextField!
#IBOutlet weak var wristCirecumference: UITextField!
#IBOutlet weak var fingerCirecumference: UITextField!
#IBOutlet weak var handCirecumference: UITextField!
#IBOutlet weak var validatedPressed: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
wristFlex.delegate = self
wristExtension.delegate = self
firstPhalanx.delegate = self
secondPhalanx.delegate = self
thirdPhalanx.delegate = self
forearmLenght.delegate = self
handLenght.delegate = self
fingerLenght.delegate = self
forearmCirecumference.delegate = self
wristCirecumference.delegate = self
fingerCirecumference.delegate = self
handCirecumference.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(textFieldTextDidChange), name: UITextField.textDidChangeNotification, object: nil)
}
// Notifications:
#objc func textFieldTextDidChange(ncParam: NSNotification) {
print("UItextFieldTextDidChange = \(ncParam)")
}
#objc func keyboardWillHide(notification: NSNotification) {
// move back the root view origin to zero
self.view.frame.origin.y = 0
}
#objc func keyboardWillShow(notification: NSNotification) {
guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
// if keyboard size is not available for some reason, dont do anything
return
}
// move the root view up by the distance of keyboard height
self.view.frame.origin.y = 0 - keyboardSize.height
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
#IBAction func validatedPressed(_ sender: AnyObject) {
if wristFlex.text == "" || wristExtension.text == "" || firstPhalanx.text == "" || secondPhalanx.text == "" || thirdPhalanx.text == "" || forearmLenght.text == "" || handLenght.text == "" || fingerLenght.text == "" || forearmCirecumference.text == "" || wristCirecumference.text == "" || fingerCirecumference.text == "" || handCirecumference.text == "" {
let alertController = UIAlertController(title: "Erreur", message: " Tous les champs ne sont pas remplis", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
alertController.addAction(alertAction)
present(alertController, animated: true, completion: nil)
return
}
dismiss(animated: true, completion: nil)
}
internal func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
print("")
return true
}
}

You can use the textFieldDidEndEditing method from the UITextfieldDelegate.
This method gets called when a user is done with his entry. Then you can access variables with textField.text
The example below is an implementation for a case where you have only one textfield. In your case you need to distinguish between the different textfields.
func textFieldDidEndEditing(_ textField: UITextField,
reason: UITextField.DidEndEditingReason){
if let value = textField.text {
print(value)
}
}
Hope this helps!

To retrieve what the user writes in the UITextFields, you can access their text properties with something like textField.text.
More specifically in your case something like wristFlex.text, or thirdPhalanx.text can work, and so on, for all of your UITextFields.
Hope this helps someone!

Related

Force unwrapping nil optional for UIImageView when transitioning to view controller

I'm running into an error when transitioning to view controllers by overriding the built-in prepare() function in Swift. I have a UIImageView for backgrounds on my screens. Here is the code for two of the view controllers in question.
import UIKit
import FirebaseAuth
class HomeVC: UIViewController {
#IBOutlet weak var signOutButton: UIButton!
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var friendsNavButton: UIButton!
#IBOutlet weak var homeNavButton: UIButton!
#IBOutlet weak var profileNavButton: UIButton!
#IBOutlet weak var bumpButton: UIButton!
#IBOutlet weak var welcomeLabel: UILabel!
#IBOutlet weak var doNotDisturbLabel: UILabel!
#IBOutlet weak var doNotDisturbButton: UIButton!
var userName = ""
var dndIsOn: Bool = false
#IBAction func dndToggled(_ sender: Any) {
dndIsOn = !dndIsOn
User.current.available = !dndIsOn
FirestoreService.db.collection(Constants.Firestore.Collections.users).document(User.current.uid).updateData([Constants.Firestore.Keys.available : !dndIsOn])
if dndIsOn {
print("DND is on!")
setupDNDUI()
} else if !dndIsOn {
print("DND is off!")
setupActiveUI()
}
}
#IBAction func signOutTapped(_ sender: Any) {
let firAuth = Auth.auth()
do {
try firAuth.signOut()
} catch let signOutError as NSError {
print ("Error signing out: %#", signOutError)
}
print("Successfully signed out")
}
#IBAction func bumpTapped(_ sender: Any) {
self.performSegue(withIdentifier: Constants.Segues.toCall, sender: self)
}
#IBAction func friendsNavTapped(_ sender: Any) {
self.performSegue(withIdentifier: Constants.Segues.toFriends, sender: self)
}
#IBAction func profileNavTapped(_ sender: Any) {
let nav = self.navigationController //grab an instance of the current navigationController
DispatchQueue.main.async { //make sure all UI updates are on the main thread.
nav?.view.layer.add(CATransition().segueFromLeft(), forKey: nil)
nav?.pushViewController(ProfileVC(), animated: false)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: true)
self.backgroundImageView.contentMode = UIView.ContentMode.scaleAspectFill
doNotDisturbLabel.isHidden = true
if !userName.isEmpty {
welcomeLabel.text = "Welcome Back, " + userName + "!"
} else {
welcomeLabel.text = ""
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .darkContent
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let friendsVC = segue.destination as? FriendsVC else {
return
}
FirestoreService.db.collection(Constants.Firestore.Collections.users).document(User.current.uid).getDocument { (snapshot, err) in
if let err = err {
print(err.localizedDescription)
} else {
let data = snapshot!.data()!
let requests = data[Constants.Firestore.Keys.requests] as? [String]
if let requests = requests {
friendsVC.requests = requests
}
}
}
}
class FriendsVC: UIViewController {
//var friends: [Friend] = User.current.friends
var friends: [User] = []
var requests: [String]?
#IBOutlet weak var requestsNumberLabel: UILabel!
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var friendRequestsButton: UIButton!
#IBOutlet weak var homeNavButton: UIButton!
#IBOutlet weak var friendsTitle: UILabel!
#IBOutlet weak var friendTableView: UITableView!
#IBOutlet weak var addFriendButton: UIButton!
#IBOutlet weak var tableViewTopConstraint: NSLayoutConstraint!
#IBAction func friendRequestsTapped(_ sender: Any) {
self.performSegue(withIdentifier: Constants.Segues.toRequests, sender: self)
}
#IBAction func homeNavTapped(_ sender: Any) {
let nav = self.navigationController //grab an instance of the current navigationController
DispatchQueue.main.async { //make sure all UI updates are on the main thread.
nav?.view.layer.add(CATransition().segueFromLeft(), forKey: nil)
nav?.pushViewController(HomeVC(), animated: false)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: true)
backgroundImageView.contentMode = UIView.ContentMode.scaleAspectFill
friendTableView.backgroundView?.backgroundColor = .white
friendsTitle.isHidden = false
UserService.getUserArray(uids: User.current.friendUids, completion: { (users) in
guard let users = users else {
print("User has no friends")
return
}
self.friends = users
self.friendTableView.reloadData()
})
guard let requests = self.requests else {
friendRequestsButton.isHidden = true
requestsNumberLabel.isHidden = true
self.tableViewTopConstraint.constant = 0
return
}
requestsNumberLabel.text = requests.count.description
// Do any additional setup after loading the view.
friendTableView.delegate = self
friendTableView.dataSource = self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let homeVC = segue.destination as? HomeVC {
homeVC.userName = User.current.firstName
} else if let requestsVC = segue.destination as? RequestsVC {
UserService.getUserArray(uids: self.requests!) { (requesters) in
if let requesters = requesters {
requestsVC.requesters = requesters
}
}
}
}
}
When my app loads into the home screen, there is no problem, and when a button is tapped to transition to FriendsVC, there is no problem. However, when I try to initiate the transition from HomeVC to ProfileVC or from FriendVC to HomeVC, I get the error: "Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value" at the self.backgroundImageView.contentMode = UIView.ContentMode.scaleAspectFill lines in my viewDidLoad methods. These segues have something in common in that these are the ones where I override the prepare() function, but I'm not sure what I'm doing wrong

Show ViewController programmatically (not working)

I got a main VC called "ViewController.swift", which is bond to my ViewController Scene in Main.storyboard.
Then I want another screen, which shows when a condition in my ViewController.swift is fulfilled.
Therefore I got a Gameover.storyboard, which has a VC Scene with Storyboard ID "overID" as well as a "GameoverViewController.swift" to handle the GameOver Scene.
Here is my code in ViewController.swift, which should open Gameover.storyboards VC Scene when the condition you see below is fulfilled:
import UIKit
class ViewController: UIViewController {
var wantedLiter = 10.00
var timer : Timer?
var actualLiter = 0.00
var timerReset = true
var preisProLiter = 1.26
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
let storyBoard: UIStoryboard = UIStoryboard(name: "Gameover", bundle: nil)
let gameoverViewController = storyBoard.instantiateViewController(withIdentifier: "overID") as! GameoverViewController
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#IBOutlet weak var preisliterLabel: UILabel!
#IBOutlet weak var euroLabel: UILabel!
#IBOutlet weak var numberLabel: UILabel!
#IBOutlet weak var numberButton: UIButton!
#IBOutlet weak var confirmButton: UIButton!
#IBAction func confirm(_ sender: Any) {
}
override func viewDidLoad() {
super.viewDidLoad()
numberLabel.text = String(round(1000*actualLiter)/1000) //initial value
preisliterLabel.text = String(preisProLiter)
// Do any additional setup after loading the view.
}
#IBAction func holdingTheButton(_ sender: Any) {
print("I am holding")
timerReset = false // reset to false since you are holding the button
guard timer == nil else { return }
timer = Timer.scheduledTimer(timeInterval: 0.005, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
#IBAction func buttonReleased(_ sender: Any) {
print("button released")
if (wantedLiter == actualLiter){
print("WIN!")
actualLiter = 0;
}
//startTime = 0.00
timer?.invalidate()
timer = nil
// timerReset = true // reset to true since you released.
}
#objc func updateTime(){
//update label every second
print("updating label ")
if (wantedLiter <= actualLiter){
print("Ooops")
actualLiter = 0;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
self.present(gameoverViewController, animated: true, completion: nil)
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
actualLiter += 0.01
numberLabel.text = String(round(1000*actualLiter)/1000)
euroLabel.text = String((round(100*actualLiter*preisProLiter)/100))
}
}
And now got you some Screenshots, which might help.
If you need more Screens, please ask.
Right now, I got following errors:
1) ViewController.swift in the upper part marked with "!!!!..."
Cannot use instance member 'storyBoard' within property initializer; property initializers run before 'self' is available
2) ViewController.swift
Cannot convert value of type 'gameoverViewController.Type' to expected argument type 'UIViewController'
3) ViewController.swift upper Part:
Use of undeclared type 'GameoverViewController'
This is how I changed the code:
import UIKit
class ViewController: UIViewController {
var wantedLiter = 10.00
var timer : Timer?
var actualLiter = 0.00
var timerReset = true
var preisProLiter = 1.26
let storyBoard: UIStoryboard = UIStoryboard(name: "Gameover", bundle: nil)
var gameoverViewController: GameoverViewController!
#IBOutlet weak var preisliterLabel: UILabel!
#IBOutlet weak var euroLabel: UILabel!
#IBOutlet weak var numberLabel: UILabel!
#IBOutlet weak var numberButton: UIButton!
#IBOutlet weak var confirmButton: UIButton!
#IBAction func confirm(_ sender: Any) {
}
override func viewDidLoad() {
super.viewDidLoad()
gameoverViewController = storyBoard.instantiateViewController(withIdentifier: "overID") as? GameoverViewController
numberLabel.text = String(round(1000*actualLiter)/1000) //initial value
preisliterLabel.text = String(preisProLiter)
// Do any additional setup after loading the view.
}
#IBAction func holdingTheButton(_ sender: Any) {
print("I am holding")
timerReset = false // reset to false since you are holding the button
guard timer == nil else { return }
timer = Timer.scheduledTimer(timeInterval: 0.005, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
#IBAction func buttonReleased(_ sender: Any) {
print("button released")
if (wantedLiter == actualLiter){
print("WIN!")
actualLiter = 0;
}
//startTime = 0.00
timer?.invalidate()
timer = nil
// timerReset = true // reset to true since you released.
}
#objc func updateTime(){
//update label every second
print("updating label ")
if (wantedLiter <= actualLiter){
print("Ooops")
actualLiter = 0;
self.present(gameoverViewController as! UIViewController, animated: true, completion: nil)
}
actualLiter += 0.01
numberLabel.text = String(round(1000*actualLiter)/1000)
euroLabel.text = String((round(100*actualLiter*preisProLiter)/100))
}
}
(not working)
And I changed the GameoverViewController type to UIViewController.
But where was my Typo?? (G instead of g)?
Move the initializer for gameoverViewController into viewDidLoad or the like and make gameoverViewController an optional or implicitly unwrapped optional (that's the ! after a type)
Should be fixed by 1.
Please show the source for GameoverViewController if this is not fixed by 1. too.

Unable to get the value back from a function to assign it to a label

I'm new to building an application but learning. I am trying to take value from the alert and save it to the label. This is to create a simple timetable to for the Week. I have two difficulties one is getting value back from the function to display it to my label which is placed behind the Button pressed on the Main.Sotryboard.
I am trying to get my value back here to assign to the Label MonB
#IBAction func MoB(_ sender: UIButton) {
ButtonTapped(sender)
}
//Trying to get my text input back here.
I am trying to get the value from the function below:
func FoodItemAdded(Food: String)
{
//return self.
//Trying to return the value from here.
}
I also looked around but don't know how to save these label values so When i close the app it still remains saved as persistent.
This is the complete Code.
import UIKit
class MenuViewController: UIViewController {
//Define all the Output Labels
#IBOutlet weak var MonB: UILabel!
#IBOutlet weak var MonL: UILabel!
#IBOutlet weak var MonD: UILabel!
#IBOutlet weak var TueB: UILabel!
#IBOutlet weak var TueL: UILabel!
#IBOutlet weak var TueD: UILabel!
#IBOutlet weak var WedB: UILabel!
#IBOutlet weak var WedL: UILabel!
#IBOutlet weak var WedD: UILabel!
#IBOutlet weak var ThuB: UILabel!
#IBOutlet weak var ThuL: UILabel!
#IBOutlet weak var ThuD: UILabel!
#IBOutlet weak var FriB: UILabel!
#IBOutlet weak var FriL: UILabel!
#IBOutlet weak var FriD: UILabel!
#IBOutlet weak var SatB: UILabel!
#IBOutlet weak var SatL: UILabel!
#IBOutlet weak var SatD: UILabel!
#IBOutlet weak var SunB: UILabel!
#IBOutlet weak var SunL: UILabel!
#IBOutlet weak var SunD: UILabel!
//Define Buttons to Enable/Disable
#IBOutlet weak var MondB: UIButton!
#IBOutlet weak var MondL: UIButton!
#IBOutlet weak var MondD: UIButton!
#IBOutlet weak var TuesB: UIButton!
#IBOutlet weak var TuesL: UIButton!
#IBOutlet weak var TuesD: UIButton!
#IBOutlet weak var WedsB: UIButton!
#IBOutlet weak var WedsL: UIButton!
#IBOutlet weak var WedsD: UIButton!
#IBOutlet weak var ThurB: UIButton!
#IBOutlet weak var ThurL: UIButton!
#IBOutlet weak var ThurD: UIButton!
#IBOutlet weak var FridB: UIButton!
#IBOutlet weak var FridL: UIButton!
#IBOutlet weak var FridD: UIButton!
#IBOutlet weak var SatuB: UIButton!
#IBOutlet weak var SatuL: UIButton!
#IBOutlet weak var SatuD: UIButton!
#IBOutlet weak var SundB: UIButton!
#IBOutlet weak var SundL: UIButton!
#IBOutlet weak var SundD: UIButton!
//Define the Edit button to enable Tap Buttons
#IBOutlet var editButton: UIBarButtonItem!
//Define all the Output Buttons
#IBAction func MoB(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func MoL(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func MoD(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func TuB(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func TuL(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func TuD(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func WeB(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func WeL(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func WeD(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func ThB(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func ThL(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func ThD(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func FrB(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func FrL(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func FrD(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func SaB(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func SaL(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func SaD(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func SuB(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func SuL(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func SuD(_ sender: UIButton) {
ButtonTapped(sender)
}
//VIEWDIDLOAD Parameters
override func viewDidLoad() {
super.viewDidLoad()
//Hide the Navigation Bar on the screen
self.navigationController?.isNavigationBarHidden = false
//Define the Title for the page
self.title = "~~~Weekly Menu~~~"
//Enable the buttons to edit
self.navigationItem.rightBarButtonItem = self.editButton
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//Disable UIButton by default
self.MondB.isEnabled = false
self.MondL.isEnabled = false
self.MondD.isEnabled = false
self.TuesB.isEnabled = false
self.TuesL.isEnabled = false
self.TuesD.isEnabled = false
self.WedsB.isEnabled = false
self.WedsL.isEnabled = false
self.WedsD.isEnabled = false
self.ThurB.isEnabled = false
self.ThurL.isEnabled = false
self.ThurD.isEnabled = false
self.FridB.isEnabled = false
self.FridL.isEnabled = false
self.FridD.isEnabled = false
self.SatuB.isEnabled = false
self.SatuL.isEnabled = false
self.SatuD.isEnabled = false
self.SundB.isEnabled = false
self.SundL.isEnabled = false
self.SundD.isEnabled = false
}
#IBAction func editEnable(_ sender: Any) {
//self.MonB.isHidden = false
// Alert stating Changes can be made
let alert = UIAlertController(title: "Message for Cook",
message: "Time to change the Menu
for Next Week",
preferredStyle:
UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Ok", style:
UIAlertAction.Style.default))
present(alert, animated: true, completion: {
//Enable Button capabilities
self.MondB.isEnabled = true
self.MondL.isEnabled = true
self.MondD.isEnabled = true
self.TuesB.isEnabled = true
self.TuesL.isEnabled = true
self.TuesD.isEnabled = true
self.WedsB.isEnabled = true
self.WedsL.isEnabled = true
self.WedsD.isEnabled = true
self.ThurB.isEnabled = true
self.ThurL.isEnabled = true
self.ThurD.isEnabled = true
self.FridB.isEnabled = true
self.FridL.isEnabled = true
self.FridD.isEnabled = true
self.SatuB.isEnabled = true
self.SatuL.isEnabled = true
self.SatuD.isEnabled = true
self.SundB.isEnabled = true
self.SundL.isEnabled = true
self.SundD.isEnabled = true
})
}
#objc func ButtonTapped(_ sender: UIButton)
{
// Create an alert
let alert = UIAlertController(
title: "What to cook?",
message: "Add The Name Of The Dish:",
preferredStyle: .alert)
// Add a text field to the alert for the new item's title
alert.addTextField(configurationHandler: nil)
// Add a "cancel" button to the alert. This one doesn't need a handler
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
// Add a "OK" button to the alert. The handler calls addNewToDoItem()
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in
if let Dish = alert.textFields?[0].text
{
self.FoodItemAdded(Food: Dish)
}
}))
// Present the alert to the user
self.present(alert, animated: true, completion: nil)
}
func FoodItemAdded(Food: String)
{
//return self.
//Trying to return the value from here.
}
//Saving the data
}
Write your function similar to this
func FoodItemAdded(Food: String)->String
{
//setting the parameter value to a variable
let string = Food
//returning new string type variable
return string
}
You can set the return value to a label like this,
self.mylabel.text = FoodItemAdded("Burger")
To store data, you can use core data/ SQLITE.
Coredata: https://youtu.be/tP4OGvIRUC4
Sqlite: https://youtu.be/c4wLS9py1rU
This is how I solved the problem:
import UIKit
import CoreData
#available(iOS 10.0, *)
class MenuViewController: UIViewController {
//Define all the Output Labels
#IBOutlet weak var MonB: UILabel!
#IBOutlet weak var MonL: UILabel!
#IBOutlet weak var MonD: UILabel!
#IBOutlet weak var TueB: UILabel!
#IBOutlet weak var TueL: UILabel!
#IBOutlet weak var TueD: UILabel!
#IBOutlet weak var WedB: UILabel!
#IBOutlet weak var WedL: UILabel!
#IBOutlet weak var WedD: UILabel!
#IBOutlet weak var ThuB: UILabel!
#IBOutlet weak var ThuL: UILabel!
#IBOutlet weak var ThuD: UILabel!
#IBOutlet weak var FriB: UILabel!
#IBOutlet weak var FriL: UILabel!
#IBOutlet weak var FriD: UILabel!
#IBOutlet weak var SatB: UILabel!
#IBOutlet weak var SatL: UILabel!
#IBOutlet weak var SatD: UILabel!
#IBOutlet weak var SunB: UILabel!
#IBOutlet weak var SunL: UILabel!
#IBOutlet weak var SunD: UILabel!
//Define Buttons to Enable/Disable
#IBOutlet weak var MondB: UIButton!
#IBOutlet weak var MondL: UIButton!
#IBOutlet weak var MondD: UIButton!
#IBOutlet weak var TuesB: UIButton!
#IBOutlet weak var TuesL: UIButton!
#IBOutlet weak var TuesD: UIButton!
#IBOutlet weak var WedsB: UIButton!
#IBOutlet weak var WedsL: UIButton!
#IBOutlet weak var WedsD: UIButton!
#IBOutlet weak var ThurB: UIButton!
#IBOutlet weak var ThurL: UIButton!
#IBOutlet weak var ThurD: UIButton!
#IBOutlet weak var FridB: UIButton!
#IBOutlet weak var FridL: UIButton!
#IBOutlet weak var FridD: UIButton!
#IBOutlet weak var SatuB: UIButton!
#IBOutlet weak var SatuL: UIButton!
#IBOutlet weak var SatuD: UIButton!
#IBOutlet weak var SundB: UIButton!
#IBOutlet weak var SundL: UIButton!
#IBOutlet weak var SundD: UIButton!
//Define the Edit button to enable Tap Buttons
#IBOutlet var editButton: UIBarButtonItem!
//Define all the Output Buttons
#IBAction func MoB(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func MoL(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func MoD(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func TuB(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func TuL(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func TuD(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func WeB(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func WeL(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func WeD(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func ThB(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func ThL(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func ThD(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func FrB(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func FrL(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func FrD(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func SaB(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func SaL(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func SaD(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func SuB(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func SuL(_ sender: UIButton) {
ButtonTapped(sender)
}
#IBAction func SuD(_ sender: UIButton) {
ButtonTapped(sender)
}
//VIEWDIDLOAD Parameters
override func viewDidLoad() {
super.viewDidLoad()
//Hide the Navigation Bar on the screen
self.navigationController?.isNavigationBarHidden = false
//Define the Title for the page
self.title = "~~~Weekly Menu~~~"
//Enable the buttons to edit
self.navigationItem.rightBarButtonItem = self.editButton
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//Disable UIButton by default
self.MondB.isEnabled = false
self.MondL.isEnabled = false
self.MondD.isEnabled = false
self.TuesB.isEnabled = false
self.TuesL.isEnabled = false
self.TuesD.isEnabled = false
self.WedsB.isEnabled = false
self.WedsL.isEnabled = false
self.WedsD.isEnabled = false
self.ThurB.isEnabled = false
self.ThurL.isEnabled = false
self.ThurD.isEnabled = false
self.FridB.isEnabled = false
self.FridL.isEnabled = false
self.FridD.isEnabled = false
self.SatuB.isEnabled = false
self.SatuL.isEnabled = false
self.SatuD.isEnabled = false
self.SundB.isEnabled = false
self.SundL.isEnabled = false
self.SundD.isEnabled = false
}
#IBAction func editEnable(_ sender: Any) {
// Alert stating Changes can be made
let alert = UIAlertController(title: "Message for Cook",
message: "Time to change the Menu for Next Week",
preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default))
present(alert, animated: true, completion: {
//Enable Button capabilities
self.MondB.isEnabled = true
self.MondL.isEnabled = true
self.MondD.isEnabled = true
self.TuesB.isEnabled = true
self.TuesL.isEnabled = true
self.TuesD.isEnabled = true
self.WedsB.isEnabled = true
self.WedsL.isEnabled = true
self.WedsD.isEnabled = true
self.ThurB.isEnabled = true
self.ThurL.isEnabled = true
self.ThurD.isEnabled = true
self.FridB.isEnabled = true
self.FridL.isEnabled = true
self.FridD.isEnabled = true
self.SatuB.isEnabled = true
self.SatuL.isEnabled = true
self.SatuD.isEnabled = true
self.SundB.isEnabled = true
self.SundL.isEnabled = true
self.SundD.isEnabled = true
})
}
#objc func ButtonTapped(_ sender: UIButton)
{
// Create an alert
let alert = UIAlertController(
title: "What to cook?",
message: "Add The Name Of The Dish:",
preferredStyle: .alert)
// Add a text field to the alert for the new item's title
alert.addTextField(configurationHandler: nil)
// Add a "cancel" button to the alert. This one doesn't need a handler
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
// Add a "OK" button to the alert. The handler calls addNewToDoItem()
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in
if let Dish = alert.textFields?[0].text {
if sender == self.MondB {
self.MonB.text = Dish
}
else if sender == self.MondL
{
self.MonL.text = Dish
}
else if sender == self.MondD
{
self.MonD.text = Dish
}
else if sender == self.TuesB
{
self.TueB.text = Dish
}
else if sender == self.TuesL
{
self.TueL.text = Dish
}
else if sender == self.TuesD
{
self.TueD.text = Dish
}
else if sender == self.WedsB
{
self.WedB.text = Dish
}
else if sender == self.WedsL
{
self.WedL.text = Dish
}
else if sender == self.WedsD
{
self.WedD.text = Dish
}
else if sender == self.ThurB
{
self.ThuB.text = Dish
}
else if sender == self.ThurL
{
self.ThuL.text = Dish
}
else if sender == self.ThurD
{
self.ThuD.text = Dish
}
else if sender == self.FridB
{
self.FriB.text = Dish
}
else if sender == self.FridL
{
self.FriL.text = Dish
}
else if sender == self.FridD
{
self.FriD.text = Dish
}
else if sender == self.SatuB
{
self.SatB.text = Dish
}
else if sender == self.SatuL
{
self.SatL.text = Dish
}
else if sender == self.SatuD
{
self.SatD.text = Dish
}
else if sender == self.SundB
{
self.SunB.text = Dish
}
else if sender == self.SundL
{
self.SunL.text = Dish
}
else if sender == self.SundD
{
self.SunD.text = Dish
}
}}))
// Present the alert to the user
self.present(alert, animated: true, completion: nil)
}

Bug when running app "unexpectedly found nil while unwrapping an Optional value"

I have a completed code for a small app I am made and are now stuck on
unexpectedly found nil while unwrapping an Optional value
Anyone have the time to help me by looking over the code and see what to do when it comes to fixing it. I am a rookie when it comes to programming.
Here is my code:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var panelWidthTextField: UITextField!
#IBOutlet weak var panelHightTextField: UITextField!
#IBOutlet weak var panelsWideTextField: UITextField!
#IBOutlet weak var panelsHightTextField: UITextField!
#IBOutlet weak var panelPitchTextField: UITextField!
#IBOutlet weak var calculateButton: UIButton!
#IBOutlet weak var resultWithLabel: UILabel!
#IBOutlet weak var resultHightLabel: UILabel!
// Removes keyboard when touch outside edit field.
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?){
view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
// Disable button when there is no value in all fields
func textFieldDidEndEditing(textField: UITextField) {
if ((panelWidthTextField.text?.isEmpty != nil) &&
(panelsWideTextField.text?.isEmpty != nil) &&
(panelHightTextField.text?.isEmpty != nil) &&
(panelPitchTextField.text?.isEmpty != nil))
{
self.calculateButton.enabled = true
} else {
self.calculateButton.enabled = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
panelWidthTextField.delegate = self
panelsWideTextField.delegate = self
panelHightTextField.delegate = self
panelsHightTextField.delegate = self
panelPitchTextField.delegate = self
}
// Sends calculation to resolution Display
func calculatePressButton(sender: AnyObject) {
let w = Double(panelWidthTextField.text!)
let sw = Double(panelsWideTextField.text!)
let pi = Double(panelPitchTextField.text!)
let sizew = SizeWidthModel(pw:w!,psw:sw!,ptc:pi!)
resultWithLabel.text=String(sizew.width())
let h = Double(panelHightTextField.text!)
let sh = Double(panelsHightTextField.text!)
let sizeh = SizeHightModel(ph:h!,psh:sh!,ptc:pi!)
resultHightLabel.text=String(sizeh.hight())
}
}
Error that comes up
I am trying do disable the one button I have until all fields are filled in.
Latest error after some fixing
Latest error
Make sure all your IBOutlest are connected with Storyboard. You can identify these connections through little circle with selected dot (Refer the attached image). Or you can print each UITextField and check the nil exception is occurred ?.
override func viewDidLoad() {
super.viewDidLoad()
print(panelWidthTextField.text)
print(panelsHightTextField.text) // I missed to connect outlet so it will throw nil

Swift: Button Enabling Not Working?

I have a button that is disabled in my view controller. I have IBActions for when two text fields are edited. I am trying to enable the button when two text fields both contain integers. I have tried to do this, but whenever I run the ios simulator, the button stays disabled even when I put integers into each text field. Why is it staying disabled? I am new to swift, so please help me out. Here is the code for my entire project:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var calculatorButton: UIButton!
#IBOutlet weak var inspirationLabel: UILabel!
#IBOutlet weak var beginningLabel: UILabel!
#IBOutlet weak var calculatorContainer: UIView!
#IBOutlet weak var answer1Label: UILabel!
#IBOutlet weak var doneButton: UIButton!
#IBOutlet weak var yourWeightTextField: UITextField!
#IBOutlet weak var calorieNumberTextField: UITextField!
#IBOutlet weak var menuExampleButton: UIButton!
#IBOutlet weak var aboutButton: UIButton!
#IBOutlet weak var calculateButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib
yourWeightTextField.delegate = self
calorieNumberTextField.delegate = self
calculateButton.enabled = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func calculatorButtonTapped(sender: AnyObject) {
calculatorContainer.hidden = false
inspirationLabel.hidden = true
beginningLabel.hidden = true
menuExampleButton.hidden = true
aboutButton.hidden = true
}
#IBAction func yourWeightEditingDidEnd(sender: AnyObject) {
yourWeightTextField.resignFirstResponder()
}
#IBAction func calorieNumberEditingDidEnd(sender: AnyObject) {
calorieNumberTextField.resignFirstResponder()
}
var yourWeightFilled = false
var calorieNumberFilled = false
func yourWeightTextFieldValueValidInt(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Find out what the text field will be after adding the current edit
let text = (yourWeightTextField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
if let intVal = text.toInt() {
self.yourWeightFilled = true
} else {
self.yourWeightFilled = false
}
return true
}
func calorieNumberTextFieldValueValidInt(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Find out what the text field will be after adding the current edit
let text = (calorieNumberTextField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
if let intVal = text.toInt() {
self.calorieNumberFilled = true
} else {
self.calorieNumberFilled = false
}
return true
}
#IBAction func yourWeightTextFieldEdited(sender: AnyObject) {
if self.yourWeightFilled && self.calorieNumberFilled {
self.calculateButton.enabled = true
}
}
#IBAction func calorieNumberTextFieldEdited(sender: AnyObject) {
if self.yourWeightFilled && self.calorieNumberFilled {
self.calculateButton.enabled = true
}
}
}
Your delegate methods are a bit mixed up -- they have to be named exactly what the caller expects, or they won't be found, so yourWeightTextFieldValueValidInt() and calorieNumberTextFieldValueValidInt() aren't being called at all. Instead you'll need to handle the edits to both text fields in a single method:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Find out what the text field will be after adding the current edit
let text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
if textField == yourWeightTextField {
yourWeightFilled = text.toInt() != nil
} else if textField == calorieNumberTextField {
calorieNumberFilled = text.toInt() != nil
}
return true
}