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

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

Related

On pressed touch Hide/Show UIImage, and count number down from 10 to 0

On every pressed touch I want UILabel to count number down one by one from 10 to 0.
Also when pressed I want to show UIImageView: "MyRocketWith", and when release the pressed touch I want to show UIImageView: "MyRocket".
class ViewController: UIViewController {
#IBOutlet weak var MyRocket: UIImageView!
#IBOutlet weak var MyRocketWith: UIImageView!
#IBOutlet weak var Countdown: UILabel!
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch: UITouch? = touches.first
if touch?.view != self.MyRocket {
self.MyRocketWith.isHidden = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
The below code shows and hides the UIImageView on click of UILabel
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var MyRocketWith: UIImageView!
#IBOutlet weak var CountDownLabel: UILabel!
#IBOutlet weak var MyRocket: UIImageView!
var count = 10
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapFunction))
CountDownLabel.isUserInteractionEnabled = true
CountDownLabel.addGestureRecognizer(tap)
MyRocket.isHidden = false
MyRocketWith.isHidden = true
MyRocketWith.tag=0
}
#IBAction func tapFunction(sender: UITapGestureRecognizer) {
print("tap working")
count = count-1
CountDownLabel.text = String(count)
if MyRocketWith.tag == 0
{
MyRocket.isHidden = true
MyRocketWith.isHidden = false
MyRocketWith.tag=1
}
else
{
MyRocket.isHidden = false
MyRocketWith.isHidden = true
MyRocketWith.tag=0
}
}
}

Get data writing in UITextField

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!

How to allow dot or comma in UITextField in calculation?

I am newbie in coding. I just started to learn #swift and trying yo make a calculation app. My problem is my UITextField doesn't work with dot or comma.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var ilkLabel: UITextField!
#IBOutlet weak var ikinciLabel: UITextField!
#IBOutlet weak var sonucLabel: UILabel!
#IBOutlet weak var ilk2Label: UITextField!
#IBOutlet weak var ikinci2Label: UITextField!
#IBOutlet weak var sonuc2Label: UILabel!
#IBOutlet weak var ilk3Label: UITextField!
#IBOutlet weak var ikinci3Label: UITextField!
#IBOutlet weak var sonuc3Label: UILabel!
var sonuc:Double = 0
var sonuc2:Double = 0
var sonuc3:Double = 0
var deneme:Double = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
#IBAction func plusBtn(_ sender: Any) {
func forTrailingZero(temp: Double) -> String {
let tempVar = String(format: "%g", temp)
return tempVar
}
deneme = Double(Int(ikinciLabel.text!)! + 100 / 100 * Int(ilkLabel.text!)!)
sonucLabel.text = String(forTrailingZero(temp: Double(ikinciLabel.text!)! / 14.56 ) )
}
#IBAction func plus2Btn(_ sender: Any) {
}
#IBAction func plus3Btn(_ sender: Any) {
}
}
I expect to make calculation like 1.4 + 2.35 but when i try the app crashes. I can only calculate whole number like 2 + 2.
#matt is right. If the text in ikinciLabel is not an Int, the app crashes. You tell it to crash by using the force unwrap operator: !.
In general
You should only force-unwrap things when you are absolutely sure that the thing you want to unwrap is not nill. In all other cases you should if-let or guard-let the optional, use the nil-coalescing operator (??) (or other ways to unwrap optionals) and handle the nil-case.
In your case
if you want to allow the user to enter floating point numbers using either a comma or a dot, you could simply replace every comma with a dot like so:
let enteredTextWithoutComma = textField.text?.replacingOccurrences(of: ",", with: ".")
This new constant is an optional. To safely make a Double out of it, do:
guard let enteredTextWithoutCommaUnwraped = enteredTextWithoutComma,
let enteredNumber = Double(enteredTextWithoutCommaUnwraped) else {
// one of the two actions didn't work. Maybe the entered phrase was not a number
// do something
return
}
// here you can use the variable enteredNumber. It is now a Double (not an Optional)
...

Swift Sliders - fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) [duplicate]

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 5 years ago.
I'm new to Swift and I was making a basic app that changes the text of a lable with the text in an inputbox and I wanted to add RGB sliders to change the color of the lable that will be changed but I got an errors soon as I try to move a slider.
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
#IBOutlet weak var OutputLabel: UILabel!
#IBOutlet weak var InputField: UITextField!
#IBOutlet weak var RedSlider: UISlider!
#IBOutlet weak var BlueSlider: UISlider!
#IBOutlet weak var GreenSlider: UISlider!
#IBOutlet weak var RedLabel: UILabel!
#IBOutlet weak var GreenLabel: UILabel!
#IBOutlet weak var BlueLabel: UILabel!
var RedColor : Float = 0
var GreenColor : Float = 0
var BlueColor : Float = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func ChangeBtn(_ sender: Any) {
OutputLabel.text = InputField.text
}
#IBAction func RedSliderAction(_ sender: UISlider) {
changeColor()
}
#IBAction func GreenSliderAction(_ sender: UISlider) {
changeColor()
}
#IBAction func BlueSliderAction(_ sender: UISlider) {
changeColor()
}
func changeOutputLableColor() {
OutputLabel.textColor = UIColor(red: CGFloat(RedColor), green: CGFloat(GreenColor), blue: CGFloat(BlueColor), alpha: 1.0)
changeLabelNumbers()
}
func changeColor() {
RedColor = RedSlider.value
GreenColor = GreenSlider.value
BlueColor = BlueSlider.value
changeOutputLableColor()
}
func changeLabelNumbers() {
let RoundedRed = String(format: "%0.0f", (RedColor * 255))
let RoundedGreen = String(format: "%0.0f", (GreenColor * 255))
let RoundedBlue = String(format: "%0.0f", (BlueColor * 255))
RedLabel.text = "\(RoundedRed)"
GreenLabel.text = "\(RoundedGreen)"
BlueLabel.text = "\(RoundedBlue)"
}
can someone help me figure it out?
You might have not connected the #IBOutlets RedSlider,BlueSlider and/or GreenSlider to the UISlider on the storyboard. That'll result in the error you are receiving.
Alternatively you might have not connected the #IBOutlets RedLabel, GreenLabel and/or BlueLabel. Just look for the line which your codes crash at and it'll hint you which one is not connected.

Update labels from unwind segue

I'm trying to change the labels of a viewController after a certain action is taken from a modal view which triggers an unwind segue.
Once unwind segue happens the labels of the current view (the one which the modal was covering) should be changed.
My current attempt at doing this is resulting in a "unexpectedly found nil while unwrapping an Optional value" error. Here is the code:
class DataViewController: UIViewController {
var experiment: NSDictionary?
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var bodyLabel: UILabel!
#IBOutlet weak var tlRightLine: UIImageView!
#IBOutlet weak var tlLeftLine: UIImageView!
#IBOutlet weak var brRightLine: UIImageView!
#IBOutlet weak var brLeftLine: UIImageView!
#IBOutlet weak var bodyTest: UITextView!
#IBAction func removeExperimentSegue(unwindSegue:UIStoryboardSegue) {
removeExperiment = true
titleLabel.text = "Done"
bodyLabel.text = "Done"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let dict: NSDictionary = experiment {
if let title = dict.objectForKey("title") as? String {
self.titleLabel!.text = title
}
if let body = dict.objectForKey("body") as? String {
self.bodyTest!.text = body
}
} else {
self.titleLabel!.text = ""
self.bodyLabel!.text = ""
}
}
}
What am I doing wrong?
I did! I ended up using a global boolean variable. I set it true on the initial load of the menu and then had it flip to false during the unwind segue.
var removeExperiment = false
class DataViewController: UIViewController {
#IBAction func removeExperimentSegue(unwindSegue:UIStoryboardSegue) {
removeExperiment = true
}
if removeExperiment == true {
doneLabel.text = "You've completed this experiment. You won't see it again unless you hit 'Reset' from the Home menu."
}
}
Hope that helps!