How can I perform addition automatically in iOS? - ios

I work on a e-commerce project and now designing basket page. I create 4 steppers for determine to quantity of products. I create labels for show cost of each products and one label for total cost.
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
#IBOutlet weak var label3: UILabel!
#IBOutlet weak var label4: UILabel!
#IBOutlet weak var label5: UILabel!
#IBAction func GmS1(_ sender: GMStepper) {
label1.text = String(sender.value*1.5)
}
#IBAction func GmS2(_ sender: GMStepper) {
label2.text = String(sender.value*0.89)
}
#IBAction func GmS3(_ sender: GMStepper) {
label3.text = String(sender.value*26)
}
#IBAction func GmS4(_ sender: GMStepper) {
label4.text = String(sender.value*4)
}
I don't want to use button but I struggling in addition total cost automatically. My codes are above. Are there anybody know : How can ı addition 4 label in 1 label automatically(without any button).
Label5 for total cost.
You can check photo for general idea.

Make a function sumValues, add all the label's value in it, and assign string of sum to label5.text. This function can be then called from all the IBAction
#IBAction func GmS4(_ sender: GMStepper) {
label4.text = String(sender.value*4)
sumValues()
}
In the function sumValues(),
set label5.text = string of sum of all the labels'.
SideNote - Make sure to initialize value of all labels to 0 in viewDidLoad().

You can try to call this method from every action
func sumAll() {
let sum = [label1,label2,label3,label4].map { Int($0.text ?? "0" ) ?? 0 }.reduce(0,+)
label5.text = "\(sum)"
}
Note: if word variable is part of the label text you may extract number from the text or declare the steppers as outlets and ask them about their current value and at this way use
let sum = [stepper1,stepper2,stepper3,stepper4].map{$0.value}.reduce(0,+)

Continuing from your previous question:
#IBAction func gmstp1(_ sender: GMStepper) {
label1.text = String(sender.value * 1.5)
calculateSum()
}
#IBAction func gmstp2(_ sender: GMStepper) {
label2.text = String(sender.value * 0.89)
calculateSum()
}
#IBAction func gmstp3(_ sender: GMStepper) {
label3.text = String(sender.value * 26.0)
calculateSum()
}
#IBAction func gmstp4(_ sender: GMStepper) {
label4.text = String(sender.value * 4.0)
calculateSum()
}
Where calculateSum is a function defined like so:
func calculateSum() {
if let text1 = label1.text, let value1 = Double(text1),
let text2 = label2.text, let value2 = Double(text2),
let text3 = label3.text, let value3 = Double(text3),
let text4 = label4.text, let value4 = Double(text4) {
let sum = value1 + value2 + value3 + value4
label6.text = String(sum)
}
}
Or if you'd prefer a one-liner:
func calculateSum() {
label5.text = String([label1, label2, label3, label4].reduce(0,{$0 + (Double($1.text ?? "0") ?? 0)}))
}

Related

Keep getting "Cannot assign to value: 'calculateBMI' is a method" when using a struct

I keep getting "Cannot assign to value: 'calculateBMI' is a method" error message when using a struct property. any way around this. This is my code from the struct:
import UIKit
struct Calculations {
var bmi : Float = 0.0
func getBMIValue() -> String {
let BMIRounded = String(format: "%.1f", bmi)
return BMIRounded
}
mutating func calculateBMI (height: Float, weight: Float) {
bmi = weight / (height * height)
}
}
and this is where I get the error message on my First Page View controller:
import UIKit
class HomeViewController: UIViewController {
var calculations = Calculations()
#IBOutlet weak var heightLabel: UILabel!
#IBOutlet weak var weightLabel: UILabel!
#IBOutlet weak var heightSlider: UISlider!
#IBOutlet weak var weightSlider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func HeightSliderChange(_ sender: UISlider) {
var height = String (format: "%.2f", sender.value)
heightLabel.text = "\(height)m"
print(height)
}
#IBAction func WeightSliderChange(_ sender: UISlider) {
var weight = String (format: "%.0f", sender.value)
weightLabel.text = "\(weight)kg"
}
#IBAction func calculatePressed(_ sender: Any) {
let height = heightSlider.value
let weight = weightSlider.value
calculations.calculateBMI = (height: height, weight: weight)
self.performSegue(withIdentifier: "GettingResults", sender: self)
}
}
The error happens on line 43 (calculations.calculateBMI)
As the error states clearly you are trying to set calculateBMI which is a function and not a variable. To fix this issue modify your calculatePressed method like this:
#IBAction func calculatePressed(_ sender: Any) {
let height = heightSlider.value
let weight = weightSlider.value
calculations.calculateBMI(height: height, weight: weight)
self.performSegue(withIdentifier: "GettingResults", sender: self)
}

Why wont the points variable display in my label?

I want the Points number to appear on a label which I have called the score. It keeps coming up with errors. I have tried multiple different ways but every time it pulls an error. Can someone resolve this, please?
//VARIABLES
var currentQuestion = 0
var rightAnswerPlacement:UInt32 = 0
var points:UInt32 = 0
//SCORE
#IBOutlet weak var score: UILabel!
//QUESTION
#IBOutlet weak var lbl: UILabel!
//BUTTON
#IBAction func action(_ sender: AnyObject)
{
if (sender.tag == Int(rightAnswerPlacement))
{
print("Right")
points += 1
}
else
{
print("Wrong")
}
if (currentQuestion != questions.count)
{
newQuestion()
}
else
{
score.text = points
}
}
You can't set a UILabel .text property (which is a String) to an Int. You need to make it a String first. Like this:
score.text = "\(points)"
The text property of the UILabel is of type String, so you need to cast points to String before setting it to score.text. Replace:
score.text = points
With:
score.text = "\(points)"
Or
score.text = String(points)
As a side note, in Swift you can write your if statements like this:
if currentQuestion != questions.count {
}

Code crashing in during runtime

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.

How to register more than one button tap using UIKit in Swift?

I am experimenting with buttons, and I have run into what is probably a simple problem. I have two buttons and two labels.
The labels generate random string values of either "A" or "B". I want the correct label to disappear if the appropriate button is selected.
I have come up with the following code, but I have run into a problem. If the letters are the same, both labels will be hidden when the corresponding button is tapped.
I understand why this is happening, I think. It's because my code is executed when buttonA is tapped once(I haven't started on button B yet, so it doesn't do anything.)
So my question is how do I require 2 taps? In other words, if label_1 and label_2 are both displayed as String "A", how would i require the user to tap buttonA twice? If more code is needed, let me know in the comments.
#IBOutlet weak var label_1: UILabel!
#IBOutlet weak var label_2: UILabel!
#IBOutlet weak var label_3: UILabel!
#IBOutlet weak var label_4: UILabel!
#IBOutlet weak var label_5: UILabel!
var visibleLetters = ["A", "B", "Z", "X"]
var text = "", text2 = "", text3 = "", text4 = "", text5 = ""
let aButton = "A", bButton = "B", zButton = "Z", xButton = "X"
var x = 0
override func viewDidLoad() {
super.viewDidLoad()
createRandomLetter(text, aSecondLetter: text2, aThirdLetter: text3, aFourthLetter: text4, aFifthLetter: text5)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func buttonA(sender: UIButton) {
if aButton == label_1.text {
label_1.hidden = true
label_1.tag += 1
}
else {
//play animation
print("play animation")
}
}
#IBAction func buttonB(sender: UIButton) {
if bButton == label_1.text {
label_1.hidden = true
}
}
#IBAction func buttonX(sender: UIButton) {
if xButton == label_1.text {
label_1.hidden = true
}
}
#IBAction func buttonZ(sender: UIButton) {
if zButton == label_1.text {
label_1.hidden = true
}
}
func createRandomLetter(individualLetter: String, aSecondLetter: String, aThirdLetter: String, aFourthLetter: String, aFifthLetter: String) {
let individuaLetter = visibleLetters[Int(arc4random_uniform(UInt32(visibleLetters.count)))],
aSecondLetter = visibleLetters[Int(arc4random_uniform(UInt32(visibleLetters.count)))],
aThirdLetter = visibleLetters[Int(arc4random_uniform(UInt32(visibleLetters.count)))],
aFourthLetter = visibleLetters[Int(arc4random_uniform(UInt32(visibleLetters.count)))],
aFifthLetter = visibleLetters[Int(arc4random_uniform(UInt32(visibleLetters.count)))]
label_1.text = individuaLetter
label_2.text = aSecondLetter
label_3.text = aThirdLetter
label_4.text = aFourthLetter
label_5.text = aFifthLetter
}
func isCorrect() {
if aButton == label_1.text {
label_1.hidden = true
label_1.tag += 1
}
else if label_1.tag == 1 && aButton == label_2.text {
}
else {
//play animation
print("play animation")
}
}
}
OK trying to figure it out what you are trying to do let's do an example. So you have 4 labels, and 2 Buttons (A,B), the labels have random generated values of A,B when you click a button you need to check if that button has the same text of the label then if it is correct we do the same with label2 if it's not correct we keep trying.
A logical way to do this can be to associate tags to your labels (that i think you are alredy doing it) and have a temporal variable to keep track of the current label for example
var temporal:String!
var current_tag:Int = 1
override func viewDidLoad() {
super.viewDidLoad()
createRandomLetter(text, aSecondLetter: text2,
aThirdLetter: text3, aFourthLetter: text4, aFifthLetter: text5)
temporal = label1.text
}
#IBAction func buttonZ(sender: UIButton) {
//Answer is correct
if zButton == temporal {
current_tag++
IsCorrect(current_tag)
}
}
func Iscorrect(tag:Int)
{
if(label2.tag == tag)
{
temporal = label2.text
}
else if(label3.tag == tag)
{
temporal = label2.text
}
else if(label4.tag == tag)
{
temporal = label2.text
}
}
Somethign like that should work, I didn't try it as I'm answering from my Ipad and I do not have access to my laptop but something like that should totally work, any doubt I can help you XD

Segmented Control in Calculator

Im trying to make a Segmented Control that holds two values, but I'm having trouble making it. I want to multiply the input by whatever side is picked in the segmented view and displayed in the label, but I keep running into errors. Any help?
#IBOutlet var input: UITextField!
#IBOutlet var output: UILabel!
#IBOutlet var controller: UISegmentedControl!
#IBAction func convert(sender: UIButton) {
}
#IBAction func change(sender: AnyObject) {
if controller.selectedSegmentIndex == 0 {
result = number1 * 1
}
if controller.selectedSegmentIndex == 1 {
result = number1 * 5
}
let number1 = Double(input.text!)
label.text = "\(result)"
}
Why you use "number1" before declaration?
Try this:
#IBOutlet var input: UITextField!
#IBOutlet var output: UILabel!
var result:Double! //fixed "cannot be applied to Double and Int." problem
#IBOutlet var controller: UISegmentedControl!
#IBAction func convert(sender: UIButton) {
}
#IBAction func change(sender: AnyObject) {
let number1 = Double(input.text!)
if controller.selectedSegmentIndex == 0 {
self.result = number1 * 1
}
if controller.selectedSegmentIndex == 1 {
self.result = number1 * 5
}
label.text = "\(result)"
}

Resources