Adding numbers from Textfields with other numbers in Textfields - ios

Right now I have 3 Textfields where users can input numbers and I want to have all 3 textfields be added together and broadcasted into either another label or textfields later down the page. Is this something that can be done?
Right now I have the following for the 3 textfields
#IBOutlet var waistText1: UITextField!
#IBOutlet var waistText2: UITextField!
#IBOutlet var waistText3: UITextField!
and for the label where the data needs to go;
#IBOutlet var wavgText: UILabel!
My first idea was something like;
wavgText.text = waistText1 + waistText2 + waistText3;

Just parse the textfields text as integer, add the values and convert back to string.
#IBOutlet var valueLabel: UILabel!
func updateValueLabel() {
let number1 = Int(waistText1?.text ?? "") ?? 0
let number2 = Int(waistText2?.text ?? "") ?? 0
let number3 = Int(waistText3?.text ?? "") ?? 0
valueLabel.text = String(number1 + number2 + number3)
}

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

Adding thousands separators to UILabel numbers

I'm trying to add thousands separators on the numbers exporting out of two UILabels on my code. I've already searched for it on here but none works for my project.
here's the part about calculation in my code so far:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var userCount: UITextField!
#IBOutlet weak var resultLabel: UILabel!
#IBOutlet weak var projectAmount: UITextField!
#IBOutlet weak var totalLabel: UILabel!
#IBAction func polculateButton(_ sender: Any) {
let usersCount = Double(self.userCount.text ?? "") ?? 0
let commissionPercentage = 0.26
let projectsAmount = Double(self.projectAmount.text ?? "") ?? 0
let totalsLabel = (usersCount * projectsAmount)
self.totalLabel.text = "\(totalsLabel)"
let resultsLabel = (usersCount * commissionPercentage * projectsAmount)
self.resultLabel.text = "\(resultsLabel)"
}
}
What code should I add here?

Cannot assign value of type 'UITextField?' to type 'String?'

First problem:
månadsSparande is a number, like 100.
When I do this:
#IBOutlet weak var månadsSparande: UITextField!
#IBAction func beräkna(_ sender: UIButton) {
totalAvkastning.text = månadsSparande
}
#IBOutlet weak var totalAvkastning: UILabel!
I get this error: Cannot assign value of type 'UITextField?' to type 'String?'
Second problem:
månadsSparande is a number, like 100.
ränta is a number, like 2.
When I do this:
#IBOutlet weak var månadsSparande: UITextField!
#IBOutlet weak var ränta: UITextField!
#IBAction func beräkna(_ sender: UIButton) {
var månad = månadsSparande + ränta
}
#IBOutlet weak var totalAvkastning: UILabel!
I get this error: Binary operator '+' cannot be applied to two 'UITextField?' operands
1- Replace: totalAvkastning.text = månadsSparande with: totalAvkastning.text = månadsSparande.text. Because you want to get the text of the text field and set it as the text of the label totalAvkastning.
2- Replace: var månad = månadsSparande + ränta with: var månad = månadsSparande.text! + ränta.text!.
A UILabel has a text property, which is the property you are interested in. Same for the UITextField.
If you want the text fields to be used with numbers only, then set the keyboard type property of these text fields to Number Pad and do the following:
if let månadsSparandeText = månadsSparande.text, let månadsSparandeInt = Int(månadsSparandeText), let räntaText = ränta.text, let räntaInt = Int(räntaText) {
var månad = månadsSparandeInt + räntaInt
}

How to split string letter separately and print in each label

I have the string like "123456". And I have 6 labels. I need to split each number and I have to print in to each label.
Like my labels are:
Lab1 Lab2 Lab3 Lab4 Lab5 Lab6 ==== In screen design
My output have to:
1 2 3 4 5 6
How can I split that each number and how I will display in my each label..I can also use 6 let or var to save each value and I can display it. But I don't know the functionality to b done.
Given text
let text = "123456"
You need to transform it into an Array of String(s).
let list = text.characters.map { String($0) }
Now you can check the array has at least 6 elements and assign each element to the text property of each label
if list.count > 5 {
lab1.text = list[0]
lab2.text = list[1]
lab3.text = list[2]
lab4.text = list[3]
lab5.text = list[4]
lab6.text = list[5]
}
You can use simple ForIn Loop :
#IBOutlet weak var lbl1: UILabel!
#IBOutlet weak var lbl2: UILabel!
#IBOutlet weak var lbl3: UILabel!
#IBOutlet weak var lbl4: UILabel!
#IBOutlet weak var lbl5: UILabel!
#IBOutlet weak var lbl6: UILabel!
let word = "123456"
func splitWord(){
// Swift 3.1
for (i,char) in word.characters.enumerated(){
switch i {
case 0:
lbl1.text = "\(char)"
case 1:
lbl2.text = "\(char)"
case 2:
lbl3.text = "\(char)"
case 3:
lbl4.text = "\(char)"
case 4:
lbl5.text = "\(char)"
case 5:
lbl6.text = "\(char)"
default:
print("Out of bound")
}
}
}

Sum of UITextfield values crashes when any field is left blank

Screenshot of simulator screen
Hello all. I just recently started trying to learn coding in Swift 2. I am trying to make a very simple app where I can add scores, push my "calculate" button and display the total in a label. I was able to do that as seen in the screenshot. The problem I have is if I don't put a score in one of the textfields and still try to calculate it, it crashes. This is my code:
class ViewController: UIViewController {
#IBOutlet weak var score1: UITextField!
#IBOutlet weak var score2: UITextField!
#IBOutlet weak var score3: UITextField!
#IBOutlet weak var total: UILabel!
#IBAction func Calculate(sender: AnyObject) {
let score1 = Int(score1.text!)!
let score2 = Int(score2.text!)!
let score3 = Int(score3.text!)!
let alltogether = (scoreone) + (scoretwo) + (scorethree)
total.text = "Your total score is \(alltogether)!"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
Could someone point me in the direction I need to look. I am thinking I need to add some sort of exemption if the field is nil. Or something along the lines of making the default int 0??? Thank you all!
let score1 : Int = Int(score1.text ?? "") ?? 0
let score2 : Int = Int(score2.text ?? "") ?? 0
let score3 : Int = Int(score3.text ?? "") ?? 0
This will yield value 0 in case your fields are empty or otherwise non-numerical (or if UITextField property .text contains nil).

Resources