Code crashing in during runtime - ios

I am learning swift3 programming but after executing my calculator app its crashing in between. Please check the below code.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var aLabel: UILabel!
#IBOutlet weak var commmon_button: UIButton!
var a: Int?
var b: Int?
var sum: Int?
var val = ""
#IBOutlet weak var text_feild: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func clik_button(_ sender: UIButton) {
val=String(sender.tag)
text_feild.text = text_feild.text! + val
}
#IBAction func fn_addition(_ sender: UIButton) {
a = Int(text_feild.text!)
}
#IBAction func fn_answer(_ sender: UIButton) {
b = Int(text_feild.text!)
sum = a! + b!
a = 0
b = 0
text_feild.text = nil
text_feild.text = String(sum!)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
During run time i am getting crash at fn_addition by saying Thread 1 breakpoint 2.1

Initiliaze your variables as below
var a = 0
var b = 0
var sum = 0
Replace your methods with below methods.
#IBAction func clik_button(_ sender: UIButton) {
guard let value = String(sender.tag), let text = text_feild.text
else {
return
}
text_feild.text = text + value
}
#IBAction func fn_addition(_ sender: UIButton) {
guard let aValue = Int(text_feild.text)
else{
return
}
a = aValue
}
#IBAction func fn_answer(_ sender: UIButton) {
guard let bValue = Int(text_feild.text)
else{return}
b = bValue
sum = a + b
a = 0
b = 0
text_feild.text = ""
text_feild.text = String(sum)
}
Suggestion: You are using same text field for taking a , b values and for showing sum result. It is better to use two different text fields for taking a and b values separately. Take a label to show sum value.

Related

Swift - the text field returns 0 even though I inserted a different number

I'm new to Swift, and I'm trying to make a little app that, given two values (a,b) returns a random number between the two numbers (a < randomnumber < b)
The user has to write the values of a and b in two different text fields and then just press a button and that's it
The problem is:
I told the NSLog to display the two values just before generating the random number because I noticed something wasn't working as it was supposed to, and the result is that apparently the second value I insert, whether it is a or b, for some (unknown) reason, equals 0 ! For example, if I write in the a-textfield the value 10 and then I insert the value 40 in the b-textfield, the NSLog displays a = 10, b = 0. If I insert the b value before, the NSLog displays b = 40, a = 0.
These are the lines of code :
#IBAction func TextAAction(sender: AnyObject) {
a = UInt32(TextA.text!)!
}
#IBAction func TextBAction(sender: AnyObject) {
b = UInt32(TextB.text!)!
}
#IBAction func randomInBetweenAction(sender: AnyObject) {
NSLog("a=%ld, b=%ld", a, b)
randomInBetween()
unHide()
Label.text = "\(randomNumberInBetween)"
}
as you can see the value a is equal to the value that is inserted in the TextA field and the value b is equal to the value that is inserted in the TextB field
the randomInBetween() is the function that generates a random number between a and b, and it does work.. the problem is that one of the values (the second one I insert) is always 0 for some reason, even if I set it to a different number!
Any ideas on why this happens and how to work it out?
#ReinerMelian this is the full code
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var Label: UILabel!
#IBOutlet weak var Button: UIButton!
#IBOutlet weak var InvariableLabel: UILabel!
#IBOutlet weak var TextA: UITextField!
#IBOutlet weak var TextB: UITextField!
#IBOutlet weak var AndLabel: UILabel!
#IBOutlet weak var Button2: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Hide()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var randomNumber = Int()
func randomNUMBER() -> Int {
randomNumber = Int(arc4random())
return randomNumber
}
func Hide() {
Label.hidden = true
}
func unHide() {
Label.hidden = false
}
var a = UInt32()
var b = UInt32()
var randomNumberInBetween = Int()
func randomInBetween() -> Int {
if b>a {
randomNumberInBetween = Int(arc4random_uniform(b - a) + a)
return randomNumberInBetween
} else {
randomNumberInBetween = Int(arc4random_uniform(a - b) + a)
return randomNumberInBetween
}
}
#IBAction func ButtonAction(sender: AnyObject) {
randomNUMBER()
unHide()
Label.text = "\(randomNumber)"
NSLog("\(randomNumber)")
}
#IBAction func TextAAction(sender: AnyObject) {
a = UInt32(TextA.text!)!
}
#IBAction func TextBAction(sender: AnyObject) {
b = UInt32(TextB.text!)!
}
#IBAction func randomInBetweenAction(sender: AnyObject) {
NSLog("a=%ld, b=%ld", a, b)
randomInBetween()
NSLog("\(randomInBetween)")
unHide()
Label.text = "\(randomNumberInBetween)"
NSLog("\(randomInBetween)")
}
}
(PS: as you can see, there is also a function that generates a random number without any sort of constraints, but that part works just fine.. the problem is with the other part of the code, the one that returns a random number between two given values (a,b) )
make sure, your outlets (TextA, TextB) and your IBAction (randomInBetweenAction) are wired up correctly, remove
#IBAction func TextAAction(sender: AnyObject) {
a = UInt32(TextA.text!)!
}
and
#IBAction func TextBAction(sender: AnyObject) {
b = UInt32(TextB.text!)!
}
and try this function on button tap:
#IBAction func randomInBetweenAction(sender: AnyObject) {
a = UInt32(TextA.text!)!
b = UInt32(TextB.text!)!
NSLog("a=%ld, b=%ld", a, b)
randomInBetween()
NSLog("\(randomInBetween)")
unHide()
Label.text = "\(randomNumberInBetween)"
NSLog("\(randomInBetween)")
}

Passing Data Through Segue & some errors

Hey guys I need some one to help me finish my app, I need to finish it before Dec 15. I'm making a Tip Calculator Project in Swift2 and It must have a settings view where I select the default tip rate. I have some issues with passing data, when I select a default tip percentage it doesn't change in the View Controller, also I want to make the app remember the default rate when I close the app and reopened. I will really appreciate that some one corrects my code and test it. Im new in this, below is the code of the two ViewControllers and a screenshot of the Main.Storyboard (Image 1) (ViewController Screenshot)
My apologies for my bad English, is not my native language
ViewController
import UIKit
class ViewController: UIViewController {
//Inputs
#IBOutlet weak var amountTextField: UITextField!
//Labels
#IBOutlet weak var TipPercentageLabel: UILabel!
#IBOutlet weak var numberOfPersonLabel: UILabel!
#IBOutlet weak var tipAmountLabel: UILabel!
#IBOutlet weak var totalBillLabel: UILabel!
#IBOutlet weak var billPerPersonLabel: UILabel!
//Slider & Stepper
#IBOutlet weak var tipSlider: UISlider!
#IBOutlet weak var personsStepper: UIStepper!
//Variables
var tipPercentage = 0.20
var numberOfPerson:Int = 1
let numberFormatter:NSNumberFormatter = NSNumberFormatter()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tipAmountLabel.text = "$0.00"
totalBillLabel.text = "Bill Total"
billPerPersonLabel.text = "$0.00"
TipPercentageLabel.text = "20.0%"
numberOfPersonLabel.text = "1"
self.amountTextField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupContainer() {
tipSlider.minimumValue = 0
tipSlider.maximumValue = 100
tipSlider.value = 20
tipSlider.addTarget(self, action: "sliderTipChanged:", forControlEvents: .ValueChanged)
personsStepper.minimumValue = 1
personsStepper.maximumValue = 30
personsStepper.value = 1
personsStepper.addTarget(self, action: "sliderPersonChanged:", forControlEvents: .ValueChanged)
amountTextField.text = ""
refreshCalculation()
}
#IBAction func OnEditingFieldBill(sender: AnyObject) {
refreshCalculation()
}
func refreshCalculation() {
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
if let amount = numberFormatter.numberFromString(amountTextField.text!) as? Double {
let tipAmount = amount * tipPercentage
let totalBill = amount + tipAmount
let billPerPerson = totalBill / Double(numberOfPerson)
numberFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
tipAmountLabel.text = numberFormatter.stringFromNumber(tipAmount)
totalBillLabel.text = numberFormatter.stringFromNumber(totalBill)
billPerPersonLabel.text = numberFormatter.stringFromNumber(billPerPerson)
} else {
tipAmountLabel.text = "-"
totalBillLabel.text = "-"
billPerPersonLabel.text = "-"
}
numberFormatter.numberStyle = NSNumberFormatterStyle.PercentStyle
numberFormatter.minimumFractionDigits = 1
numberFormatter.maximumFractionDigits = 1
TipPercentageLabel.text = self.numberFormatter.stringFromNumber(tipPercentage)
numberOfPersonLabel.text = "\(numberOfPerson)"
}
#IBAction func sliderTipChanged(sender: AnyObject) {
tipPercentage = Double(round(tipSlider.value)) / 100
refreshCalculation()
}
#IBAction func StepperPersonChanged(sender: AnyObject) {
numberOfPerson = Int(round(personsStepper.value))
refreshCalculation()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let id = segue.identifier {
if id == "show settings" {
if let SettingsViewController = segue.destinationViewController as? SettingsViewController {
}
}
}
}
}
Settings View Controller
import UIKit
class SettingsViewController: UIViewController {
#IBOutlet weak var tipControl: UISegmentedControl!
var tipRates:Double?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func DefaultRate(sender: AnyObject) {
var tipRate = [5, 10, 15, 20, 25, 30]
var tipRates = Double(tipRate[tipControl.selectedSegmentIndex])
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let id = segue.identifier {
if id == "goBackToViewController" {
if let ViewController = segue.destinationViewController as? ViewController {
if let tip = tipRates {
ViewController.tipPercentage = tip/100
}
}
}
}
---- Edit from comments ----
I think the reason it is not updating as you would like is due to a minor error with this line.
var tipRates = Double(tipRate[tipControl.selectedSegmentIndex])
Inside of your DefaultRate action function for the UISegmentedControl
Using var is a redeclaration of the same variable name, thus what you are trying to pass in the prepareForSegue is an empty variable.
This function should be changed to:
#IBAction func DefaultRate(sender: AnyObject) {
var tipRate = [5, 10, 15, 20, 25, 30]
tipRates = Double(tipRate[tipControl.selectedSegmentIndex])}
Hopefully this will now solve the error.
---- End Edit ----
From what I can see in the viewDidLoad function of your viewController, you are setting the tip label, and not updating the value based on the variable var tipPercentage.
TipPercentageLabel.text = "20.0%"
is setting the value display to always be 20.0%, you could use this here.
var tipDisplay = tipPercentage * 100
TipPercentageLabel.text = "\(tipDisplay)%"
This should update the displayed value in the label, however you never call on your other functions to recalculate the amount etc.
Thus you should also be calling on
func setupContainer()
or
func refreshCalculation()
within your ViewDidLoad().
In terms of remembering the default value when the app is closed you should look into using NSUserDefaults.
Some information regarding NSUserDefaults can be found here, which explains implementing small amounts of saved data and can be implemented in your case quite simply.

Arrays in Swift - How to add images

I am making an application that keeps score from 1 to 20 and then displays an image if the score is >= 21. However I don't know how to go about this, I have a label that displays the users score in integers. Is there a way that I can add an image to the array after 20? Or is there a way to add a string when score >= 21 that says "Bullseye" either the string or image. I just dont know the best way to do this any help?
import UIKit
class ViewController: UIViewController {
//Below are all of the labels at the top of AZG
#IBOutlet weak var user1name: UILabel!
#IBOutlet weak var user2name: UILabel!
#IBOutlet weak var lbl_currentPlayer: UILabel!
#IBOutlet weak var user1score: UILabel!
#IBOutlet weak var user2score: UILabel!
//Below are all the declared variables
var usernames = ["Big Meat ", "J Hooks "]
var currentPlayer = 0
var scores = [0,0]
var count = 0
var sdCount = 0
override func viewDidLoad() {
super.viewDidLoad()
setupGame()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func newGame() {
user1score.text = "\(count)"
user2score.text = "\(count)"
user1name.text = "\(usernames[0])"
user2name.text = "\(usernames[1])"
lbl_currentPlayer.text = usernames[currentPlayer]
scores = [0,0]
}
func setupGame() {
user1score.text = "\(count)"
user2score.text = "\(count)"
user1name.text = "\(usernames[0])"
user2name.text = "\(usernames[1])"
lbl_currentPlayer.text = usernames[currentPlayer]
}
func updateTurn() {
lbl_currentPlayer.text = usernames[currentPlayer]
user1score.text = "\(scores[0])"
user2score.text = "\(scores[1])"
}
func attackTurnUpdate() {
currentPlayer = 1 - currentPlayer
}
func resetAttackTurn() {
currentPlayer = 1 - currentPlayer
}
func missedNextTurn() {
currentPlayer = 1 - currentPlayer
}
func suddenDeath() {
sdCount = sdCount++
}
func takeStepBack() {
}
func bullseyeDisplay() {
}
#IBAction func hitSingle(sender: AnyObject) {
scores[currentPlayer]++
updateTurn()
}
#IBAction func nextTurn(sender: AnyObject) {
currentPlayer = 1 - currentPlayer
updateTurn()
}
Just add the image to your view in interface builder (with an appropriate IBOutlet in your code) and set "Hidden" on it.
Then when you want to display the image, just change the value of hidden:
my image.hidden = false

Prepare for segue, passing data

Hey guys I need some help here with my code, please take a look to the images to see what I see. I'm making a Tip Calculator Project in Swift and I must have a settings view where I select the default tip rate. I have some errors and I must fix that as soon as posible. I will really appreciate that some one corrects my code and test it. Below is the code of the two ViewControllers, I did not post the image of the Settings View Controller because the website does not let me post more than two links until I get more reputation.
The error in Xcode:
Storyboard: Check the images I have some errors at the first lines.
import UIKit
class ViewController: UIViewController, SettingDelegate {
// Inputs
#IBOutlet weak var amountTextField: UITextField!
//Labels
#IBOutlet weak var TipPercentageLabel: UILabel!
#IBOutlet weak var numberOfPersonLabel: UILabel!
#IBOutlet weak var tipAmountLabel: UILabel!
#IBOutlet weak var totalBillLabel: UILabel!
#IBOutlet weak var billPerPersonLabel: UILabel!
//Slider & Stepper
#IBOutlet weak var tipSlider: UISlider!
#IBOutlet weak var personsStepper: UIStepper!
//Variables
var tipPercentage : Double = NSUserDefaults.standardUserDefaults().doubleForKey("DefaultTipRate") ?? 0.20
var numberOfPerson:Int = 1
let numberFormatter:NSNumberFormatter = NSNumberFormatter()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tipAmountLabel.text = "$0.00"
totalBillLabel.text = "Bill Total"
billPerPersonLabel.text = "$0.00"
TipPercentageLabel.text = "20.0%"
numberOfPersonLabel.text = "1"
self.amountTextField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupContainer() {
tipSlider.minimumValue = 0
tipSlider.maximumValue = 100
tipSlider.value = 20
tipSlider.addTarget(self, action: "sliderTipChanged:", forControlEvents: .ValueChanged)
personsStepper.minimumValue = 1
personsStepper.maximumValue = 30
personsStepper.value = 1
personsStepper.addTarget(self, action: "sliderPersonChanged:", forControlEvents: .ValueChanged)
amountTextField.text = ""
refreshCalculation()
}
#IBAction func OnEditingFieldBill(sender: AnyObject) {
refreshCalculation()
}
func refreshCalculation() {
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
if let amount = numberFormatter.numberFromString(amountTextField.text!) as? Double {
let tipAmount = amount * tipPercentage
let totalBill = amount + tipAmount
let billPerPerson = totalBill / Double(numberOfPerson)
numberFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
tipAmountLabel.text = numberFormatter.stringFromNumber(tipAmount)
totalBillLabel.text = numberFormatter.stringFromNumber(totalBill)
billPerPersonLabel.text = numberFormatter.stringFromNumber(billPerPerson)
} else {
tipAmountLabel.text = "-"
totalBillLabel.text = "-"
billPerPersonLabel.text = "-"
}
numberFormatter.numberStyle = NSNumberFormatterStyle.PercentStyle
numberFormatter.minimumFractionDigits = 1
numberFormatter.maximumFractionDigits = 1
TipPercentageLabel.text = self.numberFormatter.stringFromNumber(tipPercentage)
numberOfPersonLabel.text = "\(numberOfPerson)"
}
#IBAction func sliderTipChanged(sender: UISlider) {
tipPercentage = Double(round(tipSlider.value)) / 100
refreshCalculation()
}
#IBAction func StepperPersonChanged(sender: UIStepper) {
numberOfPerson = Int(round(personsStepper.value))
refreshCalculation()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let SettingsViewController = segue.destinationViewController as?SettingsViewController {
SettingsViewController.delegate = self
refreshCalculation()
}
}
}
The SettingsViewController below:
import UIKit
protocol SettingDelegate {
func tipPercentageChanged(newValue : Double)
}
class SettingsViewController: UIViewController {
var destName : String!
var delegate : SettingDelegate?
#IBOutlet weak var tipControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func DefaultRate(sender: AnyObject) {
var tipRates = [0.05, 0.10, 0.15, 0.20, 0.25, 0.30]
let tipRate = tipRates[tipControl.selectedSegmentIndex]
delegate?.tipPercentageChanged(tipRate)
NSUserDefaults.standardUserDefaults().setDouble(tipRate, forKey: "DefaultTipRate")
NSUserDefaults.standardUserDefaults().synchronize()
}
/
For your first error:
When a viewController conforms to a protocol, it needs to implements the methods the protocol implements. In your case, define you should have
func tipPercentageChanged(newValue : Double) {
//save the new value here
}
The first error should go away.
It looks like you are presenting the SettingsViewController using a modal transition, so you can use
self.dismissViewControllerAnimated(true, completion: {})

Updating app to swift, trying to display a percentage

I am updating my app for swift. I am trying to display a percentage once the "calculate" button is pushed.
So far I have:
#IBAction func calculateButton(sender: UIButton) {
var calculated = (correctNumber / correctNumber + incorrectNumber * 100 )
calculateLabel.text = "\(calculated)"
}
Which I know is incorrect. How do I convert this to a percentage?
Full code below:
import UIKit
class ViewController: UIViewController {
var correctNumber = 0
var incorrectNumber = 0
var verbalNumber = 0
var visualNumber = 0
var tactileNumber = 0
//rightnumber____________________________________
#IBOutlet weak var correctLabel: UILabel!
#IBAction func correctUpButton(sender: UIButton) {
correctNumber += 1
correctLabel.text = "\(correctNumber)"
}
#IBAction func correctDownButton(sender: UISwipeGestureRecognizer) {
correctNumber -= 1
correctLabel.text = "\(correctNumber)"
}
//------------------------------------------------
//incorrectNumber________________________________
#IBOutlet weak var incorrectLabel: UILabel!
#IBAction func incorrectUpButton(sender: UIButton) {
incorrectNumber += 1
incorrectLabel.text = "\(incorrectNumber)"
}
#IBAction func incorrectDownButton(sender: UISwipeGestureRecognizer) {
incorrectNumber -= 1
incorrectLabel.text = "\(incorrectNumber)"
}
//end-------------------------------------------------
//verbalNumber________________________________
#IBOutlet weak var verbalLabel: UILabel!
#IBAction func verbalUpButton(sender: UIButton) {
verbalNumber += 1
verbalLabel.text = "\(verbalNumber)"
}
#IBAction func verbalDownButton(sender: UISwipeGestureRecognizer) {
verbalNumber -= 1
verbalLabel.text = "\(verbalNumber)"
}
//end-------------------------------------------------
//visualNumber________________________________
#IBOutlet weak var visualLabel: UILabel!
#IBAction func visualUpButton(sender: UIButton) {
visualNumber += 1
visualLabel.text = "\(visualNumber)"
}
#IBAction func visualDownButton(sender: UISwipeGestureRecognizer) {
visualNumber -= 1
visualLabel.text = "\(visualNumber)"
}
//end-------------------------------------------------
//tactileNumber________________________________________
#IBOutlet weak var tactileLabel: UILabel!
#IBAction func tactileUpButton(sender: UIButton) {
tactileNumber += 1
tactileLabel.text = "\(tactileNumber)"
}
#IBAction func tactileDownButton(sender: UISwipeGestureRecognizer) {
tactileNumber -= 1
tactileLabel.text = "\(tactileNumber)"
}
//end--------------------------------------------------
//calculate______________________________________________
#IBOutlet weak var calculateLabel: UILabel!
#IBAction func calculateButton(sender: UIButton) {
var calculated = (correctNumber / correctNumber + incorrectNumber * 100 )
calculateLabel.text = "\(calculated)"
}
//end----------------------------------------------------
//reset
#IBAction func resetButton(sender: UIButton) {
correctNumber = 0
correctLabel.text = ""
incorrectNumber = 0
incorrectLabel.text = ""
verbalNumber = 0
verbalLabel.text = ""
visualNumber = 0
visualLabel.text = ""
tactileNumber = 0
tactileLabel.text = ""
calculateLabel.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
If i understand it correctly you need change line like this one:
var calculated = correctNumber / (correctNumber + incorrectNumber) * 100

Resources