Use swift stepper to multiply my original number not previous number - ios

Here's my code.
My need is if the price label have had number
When pressing add from stepper
I need stepper value to multiply my price number
but I encounter this situation
The price label won't multiply my original number
like if price number originally is 50
I would like to show 50,100,150,200,250
not like this 50 ,100 ,300,400
#IBOutlet weak var stepperValue: UILabel!
#IBOutlet weak var price: UILabel!
#IBAction func stepper(_ sender: UIStepper) {
let count = Int(sender.value)
stepperValue.text = String(count)
let price = Int(price.text!)!
price.text? = String(price * count)
}
Is there proper way to solve my logical problem?

You need to store original value somewhere and use it for incrementation.
E.g.
#IBOutlet weak var stepperValue: UILabel!
#IBOutlet weak var price: UILabel!
private var originalPrice: Int = 50 // or whatever you want
#IBAction func stepper(_ sender: UIStepper) {
let count = Int(sender.value)
stepperValue.text = String(count)
price.text = String(originalPrice * count)
}

Related

how to multiply label data with an Int?

Im trying to be able to multiply the data in the label of price(1-3) by the counterValue to show the price for for each option that is selected
So far my code can multiply the counterValue by the factor of the selected optionBtn(1-3) when selected
What Im trying to do is multiply the counter value by the label data of the Price labels
All price labels are Floats I've tried using this code Int(Float(modifyItems.cart.price1)) to replace the factor variable in the 'if statements' but still no success
SideNote: The data that populates the labels in the ModifyVC is passed from another VC. A delegate passes the data into the ModifyVC and the data is retrieved from cloud Firestore (as seen in the viewDidLoad)
thank in advanced for any help that is given
class ModifyViewController: UIViewController {
private var counterValue = 1
var lastSelectedWeightButton = RoundButton()
var modifyItems: Cart!
#IBOutlet weak var price1: UILabel!
#IBOutlet weak var price2: UILabel!
#IBOutlet weak var price3: UILabel!
#IBOutlet weak var weight1: UILabel!
#IBOutlet weak var weight2: UILabel!
#IBOutlet weak var weight3: UILabel!
#IBOutlet weak var lblQty: UILabel!
#IBOutlet weak var modifyTotal: UILabel!
#IBOutlet weak var option1: RoundButton!
#IBOutlet weak var option2: RoundButton!
#IBOutlet weak var option3: RoundButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.numberStyle = .decimal
price1.text = "$\(formatter.string(for: modifyItems.cart.price1)!)"
price2.text = "$\(formatter.string(for: modifyItems.cart.price2)!)"
price3.text = "$\(formatter.string(for: modifyItems.cart.price3)!)"
weight1.text = modifyItems.cart.weight1
weight2.text = modifyItems.cart.weight2
weight3.text = modifyItems.cart.weight3
}
#IBAction func minusQty(_ sender: AnyObject) {
if(counterValue != 1){
counterValue -= 1
}
self.lblQty.text = "\(counterValue)"
var factor = 1
if option1.isSelected {
factor = 13
} else if option2.isSelected {
factor = 39
} else if option3.isSelected {
factor = 72
}
modifyTotal.text = "$\(factor * counterValue)"
print("Decrease Quantity")
}
}
class Cart {
var cart: Items!
init(cart: Items) {
self.cart = cart
}
}
You just store the label data to (Int or Float).
var total = 0
if modifyTotal.text != " " {
total = Int(modifyTotal.text.replacingOccurrences(of: "$", with: ""))!
}
let finalTotalValue = total + (factor * CounterValue)
modifyTotal.text = "$\(finalTotalValue)"
You can use NSExpression to evaluate your expression like
let nExpression = "1 * 5"
let expression = NSExpression(format: nExpression)
var result = expression.expressionValue(with: nil, context: nil) as? Int

Calculating and displaying as label

I want to calculate Runs per Overs and display on a Run Rate Label.
As you can see in my code, the Run Rate will change as i'm using steppers for Runs and Overs.
The run rate need to be displayed up to 2 decimal points (eg. 4.50 or 10.74 etc.)
I want to create function but I don't know how to calculate.
How can I do this?
// RUNS
var runsInt = 0
var oversFloat: Float = 0.0
var runRate: Double = 0.0
#IBOutlet weak var runsLabel: UILabel!
#IBOutlet weak var displayRunsLabel: UILabel!
#IBOutlet weak var oversLabel: UILabel!
#IBOutlet weak var oversRectangle: UILabel!
#IBOutlet weak var displayOversLabel: UILabel!
#IBOutlet weak var runRateLabel: UILabel!
#IBOutlet weak var displayRunRateLabel: UILabel!
#IBAction func RunStepper(_ sender: UIStepper) {
let runsValue = Int(sender.value)
displayRunsLabel.text = String(runsValue)
}
// OVERS
#IBAction func OversStepper(_ sender: UIStepper) {
let value = Int(sender.value)
let remainder = value % 10
if remainder == 6 {
sender.value = Double(value + 4)
} else if remainder == 9 {
sender.value = Double(value - 4)
}
displayOversLabel.text = String(format: "%.1f", sender.value / 10)
}
I used this page for information on calculating run rate.
runRate = (total runs scored)/(total overs faced)
Note: If overs is 47.5, the stepper value will be 475.0 and
oversInt will be set to 475. When calculating runRate, 47.5
actually represents 47 5/6 which we can calculate as
Double(oversInt / 10) + Double(oversInt % 10) / 6
Create a function called calculateRunRate and
add property observers (didSet) to runsInt and oversInt to trigger the calculation of runRate. Then anytime either of those values changes, runRate will be recalculated and the displayRunRate label will be updated.
// RUNS
var runsInt = 0 {
didSet {
calculateRunRate()
}
}
#IBOutlet weak var runsLabel: UILabel!
#IBOutlet weak var displayRunsLabel: UILabel!
#IBAction func RunStepper(_ sender: UIStepper) {
runsInt = Int(sender.value)
displayRunsLabel.text = String(runsInt)
}
// OVERS
var oversInt = 0 {
didSet {
calculateRunRate()
}
}
#IBOutlet weak var oversLabel: UILabel!
#IBOutlet weak var oversRectangle: UILabel!
#IBOutlet weak var displayOversLabel: UILabel!
#IBAction func OversStepper(_ sender: UIStepper) {
var value = Int(sender.value)
let remainder = value % 10
if remainder == 6 {
value += 4
} else if remainder == 9 {
value -= 4
}
sender.value = Double(value)
oversInt = value
displayOversLabel.text = String(format: "%.1f", sender.value / 10)
}
// RUN RATE
var runRate = 0.0
let maxOvers = 40.0
#IBOutlet weak var runRateLabel: UILabel!
#IBOutlet weak var displayRunRateLabel: UILabel!
#IBOutlet weak var displayRequiredRunRateLabel: UILabel!
func calculateRunRate() {
var oversDouble = 0.0
// Don't divide by zero
if oversInt == 0 {
// can this even happen?
// set runRate to some value that makes sense
runRate = 0.0
} else {
oversDouble = Double(oversInt / 10) + Double(oversInt % 10) / 6
runRate = Double(runsInt) / oversDouble
}
displayRunRateLabel.text = String(format: "%.2f", runRate)
// required run rate
let targetScore = Int(targetScoreLabel.text ?? "") ?? 0
var requiredRunRate = 0.0
if oversDouble < maxOvers {
requiredRunRate = Double(targetScore - runsInt) / (maxOvers - oversDouble)
}
displayRequiredRunRateLabel.text = String(format: "%.2f", requiredRunRate)
}

Bill Amount for Tip Calc. is not influencing tip and total #'s

Below is my code and a picture. I have looked at previous questions regarding smilier issues but could not find help.
Furthermore, where in my code is the error in which when I enter a number in the bill field it should begins to calculate the tip amount and fill in the tip and total numbers?
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var billField: UITextField!
#IBOutlet weak var tipLabel: UILabel!
#IBOutlet weak var totalLabel: UILabel!
#IBOutlet weak var tipControl: UISegmentedControl!
#IBAction func onTap(sender: AnyObject){
view.endEditing(true)
}
#IBAction func calculateTip(sender: AnyObject) {
let tipPercentages = [0.18, 0.2, 0.25]
let bill = Double(billField.text!)!
let tip = bill * tipPercentages[tipControl.selectedSegmentIndex]
let total = bill + tip
tipLabel.text = String (format: "$%.2f", tip)
totalLabel.text = String (format: "$%.2f", tip)
}
}

How do I change what property to use in function of action based off of sender in Swift 4

#IBOutlet weak var weekdaysHoursSliderOutlet: UISlider!
#IBOutlet weak var weekdaysHoursLabelOutlet: UILabel!
#IBOutlet weak var weekdaysHoursNumberLabel: UILabel!
#IBOutlet weak var weekdendsHoursSliderOutlet: UISlider!
#IBOutlet weak var weekendsHoursLabelOutlet: UILabel!
#IBOutlet weak var weekendsHoursNumberLabel: UILabel!
#IBAction func weekendsHoursSliderChange(_ sender: UISlider) {
let currentValue: Int = Int(sender.value)
weekendsHoursNumberLabel.text = ("\(currentValue)")
if(currentValue == 1){
weekendsHoursLabelOutlet.text = ("Hour Per Day")
}
else{
weekendsHoursLabelOutlet.text = ("Hours Per Day")
}
}
I would want to change that to weekdays if say the weekdaysHourSliderOutlet called an on change Action. I plan on implementing more than just weekends and weekdays so I don't want a bunch of redundant code. I was thinking of using a dictionary of some sort but couldn't get it hooked up correctly. Thank you in advance!
func viewDidLoad() {
weekdaysHoursSliderOutlet.tag = 1
weekdendsHoursSliderOutlet.tag = 2
}
#IBAction func sliderChanged(_ sender: UISlider) {
if sender.tag == 1 {
//handle weekdaysHoursSliderOutlet
}
else {
//handle weekdendsHoursSliderOutlet
}
}

Use of Unresolved Identifier with Segmented Control

I have a scene in my app that I want to do basic math between two slider bars and a segmented control that the user picks. I am trying to do the math between variables under the segmented controls, but Xcode is giving me a (!) stating
Use of unresolved identifier "xxxx"
with whatever variable I'm trying to add.
My code is:
import UIKit
class DopamineCalculator: UIViewController {
//slider outlets
#IBOutlet weak var slider: UISlider!
#IBOutlet weak var sliderone: UISlider!
//segmentoutlet
#IBOutlet weak var segmentoutlet: UISegmentedControl!
//LABELS
//weight label
#IBOutlet weak var weightlabel: UILabel!
//dosage label
#IBOutlet weak var dosagemg: UILabel!
//Drip Rate Answer Label
#IBOutlet weak var dripanswer: UILabel!
//ACTIONS!!
//weight slider action
#IBAction func weightslider(sender: UISlider) {
let weight = Int(sender.value)
//converts to kgs
let kgs = Int(sender.value) / Int(2.2)
weightlabel.text = "\(weight) lbs"
}
//Dosage Desired dosage slider
#IBAction func dosagedesired(sender: UISlider) {
let dosage = Int(sender.value)
dosagemg.text = "\(dosage) mg"
}
//CONCENTRATION OPTIONS
#IBAction func concentrationoption(sender: UISegmentedControl) {
switch segmentoutlet.selectedSegmentIndex
{
case 0:
dripanswer.text = (kgs) * (dosage) / 800
case 1:
dripanswer.text = "1600";
case 2:
dripanswer.text = "3200";
default:
break;
}
}
What I am trying to do is kgs x dosage / 800 respectively for each case. I can not find an adequate solution online to the unresolved identifier issue.
#IBOutlet ...
// Add variables to be reachable for all methods
var dosage : Int = 0
var kgs : Double = 0.0
var divisor : Double = 800.0
#IBAction func dosagedesired(sender: UISlider) {
// prepend self to variable as it is used
self.dosage = Int(sender.value)
dosagemg.text = "\(self.dosage) mg"
// adding the calculation here
let result = self.kgs * Double(self.dosage) / self.divisor
dripanswer.text = "\(result)"
}
#IBAction func weightslider(sender: UISlider) {
let weight = Int(sender.value)
// converts to kgs
// the same here
self.kgs = Int(sender.value) / Int(2.2)
// adding the calculation here
let result = self.kgs * Double(self.dosage) / self.divisor
dripanswer.text = "\(result)"
}
#IBAction func concentrationoption(sender: UISegmentedControl) {
switch segmentoutlet.selectedSegmentIndex
{
case 0:
self.divisor = 800.0
case 1:
self.divisor = 1600.0
case 2:
self.divisor = 3200.0
default:
self.divisor = 800.0
}
// finally the calculation
let result = self.kgs * Double(self.dosage) / self.divisor
dripanswer.text = "\(result)"
}
You should declare the variables kgs and dosage outside of any method i.e. at the class level, along with your outlets
//slider outlets
#IBOutlet weak var slider: UISlider!
#IBOutlet weak var sliderone: UISlider!
//segmentoutlet
#IBOutlet weak var segmentoutlet: UISegmentedControl!
//LABELS
//weight label
#IBOutlet weak var weightlabel: UILabel!
//dosage label
#IBOutlet weak var dosagemg: UILabel!
//Drip Rate Answer Label
#IBOutlet weak var dripanswer: UILabel!
// You should declare the variables here:
var kgs = 0
var dosage = 0
And when you use kgs and dosage inside your methods, remove the word let because you're not declaring a variable.
The reason you do this is that you can't access variables declared in a method in another method. In the concentrationoption method, you can't access dosage, which is defined in dosagedesired method.

Resources