Getting values from labels and adding together in another label - ios

I'm trying to get the int values from my labels and pass them to another label and add them together. In the code below, kicklabel, handballlabel, marklabel, etc., all need to add up and equal into fantasylabel. Based on how this code is set up, I'm not sure how to perform that.
I want to be able to add more lines of labels also, so that any amount of the array of labels add to a fantasy label.
Here's the code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var kickLabel1: UILabel!
#IBOutlet weak var handballLabel1: UILabel!
#IBOutlet weak var markLabel1: UILabel!
#IBOutlet weak var tackleLabel1: UILabel!
#IBOutlet weak var goalLabel1: UILabel!
#IBOutlet weak var pointLabel1: UILabel!
#IBOutlet weak var freeForLabel1: UILabel!
#IBOutlet weak var freeAgainstLabel1: UILabel!
#IBOutlet weak var fantasyLabel: UILabel!
var counters: [UILabel: Int] = [:]
override func viewDidLoad() {
super.viewDidLoad()
for label: UILabel in [kickLabel1,handballLabel1,markLabel1,tackleLabel1,goalLabel1,pointLabel1, freeForLabel1, freeAgainstLabel1, fantasyLabel] {
counters[label] = 0
for direction: UISwipeGestureRecognizerDirection in [.up, .down, .left, .right] {
let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(didSwipe(_:)))
swipeGesture.direction = direction
label.addGestureRecognizer(swipeGesture)
label.isUserInteractionEnabled = true
label.isMultipleTouchEnabled = true
}
}
}
#objc func didSwipe(_ gestureRecognizer: UISwipeGestureRecognizer) {
guard let label = gestureRecognizer.view as? UILabel else { return }
debugPrint("\(gestureRecognizer.direction)")
switch gestureRecognizer.direction {
case .up:
counters[label] = counters[label]! + 10
print(counters)
case .down:
counters[label] = 0
print(counters)
case .left:
counters[label] = counters[label]! - 1
print(counters)
case .right:
counters[label] = counters[label]! + 1
print(counters)
default:
counters[label] = 0
}
label.text = "\(counters[label]!)"
}
}

At the end of your didSwipe you need to sum all of the Int values stored in your counters dictionary. Then update your fantasy label with that sum.
let sum = counters.reduce(0) { $0 + $1.value }
fantasyLabel.text = "\(sum)"
And you probably don't want a gesture on the fantasy label since that value is read-only based on the sum of the other data.
I would also get rid of the individual label outlets except for the fantasy label. Use an IBOutletCollect to store an array of UILabel.

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?

Not woking UIView ishidden after change UILabel text value in swift

I want to change uilabel value and show uiview that has hide like a popup windows.
When I touch a button, that code print "setPopupView 0".
but doesn't show settingView.
and I touch a button again.
print "setPopupView 0" and show settingView.
so When "settingLabelValueUnit text" has changed not show settingView,
but when "settingLabelValueUnit text" has not changed show settingView.
(It means "settingLabelValue text" is same as input value)
I don't know why.
Anyone can help me?
Thank you
here is my swift code.
class ViewController: UIViewController {
#IBOutlet weak var workoutScrollView: UIScrollView!
#IBOutlet weak var settingView: UIView!
#IBOutlet weak var settingLabelValueUnit: UILabel!
#IBOutlet weak var imgSettingBGcal: UIImageView!
#IBOutlet weak var imgSettingBGdis: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.imgSettingBGcal.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(calSettingClick)))
self.imgSettingBGdis.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(disSettingClick)))
}
func calSettingClick(sender: UITapGestureRecognizer) {
setPopupView(0)
}
func disSettingClick(sender: UITapGestureRecognizer) {
setPopupView(1)
}
func showPopup (_ settype:Int) {
switch settype {
case 0:
print("setPopupView 0")
self.settingLabelValueUnit.text = "Set1"
self.workoutScrollView.isHidden = true
self.settingView.isHidden = false
case 1:
print("setPopupView 0")
self.settingLabelValueUnit.text = "Set2"
self.workoutScrollView.isHidden = true
self.settingView.isHidden = false
}
}
}

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.

UIBottom Text Field not setting

I have a label that displays a random emoji, and then I have 4 UIButtons. Each one will display a random emoji, and one of the 4 will display the same emoji as the one on the label. Its a matching game.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var faceLabel: UILabel!
#IBOutlet weak var scoreLabel: UILabel!
var randomEmojiNum: UInt32 = arc4random_uniform(6) + 1
override func viewDidLoad() {
super.viewDidLoad()
faceLabel.text = genRanNum()
}
func genRanNum() -> String{
switch randomEmojiNum{
case 1: return "😀"
case 2: return "😅"
case 3: return "😉"
case 4: return "😁"
case 5: return "😂"
case 6: return "😄"
default: break
}
return "Default"
}
func correctAnswerGen() {
var correct: UInt32 = arc4random_uniform(4)
switch correct{
case 0: topLeftAnswer.titleLabel?.text = genRanNum()
case 1: topRightAnswer.titleLabel?.text = genRanNum()
case 2: bottomRightAnswer.titleLabel?.text = genRanNum()
case 3: bottomLeftAnswer.titleLabel?.text = genRanNum()
default: break
}
}
#IBOutlet weak var topLeftAnswer: UIButton!
#IBOutlet weak var topRightAnswer: UIButton!
#IBOutlet weak var bottomLeftAnswer: UIButton!
#IBOutlet weak var bottomRightAnswer: UIButton!
}
But every time I run it, it doesn't go as expected. Right now I'm assigning randomly one of the 4 UIButton outlets to be set to the same emoji as the one on the label, however none of the outlets set!
Whenever I run it looks like it is being selected. None of the buttons ever get set! I have a hunch it has something to do with the outlets being set and me editing the value after they are set. However, if i knew, i wouldn't be asking for help! Haha cheers!
Instead of topLeftAnswer.titleLabel?.text just use:
topLeftAnswer.setTitle("emoji", forState: UIControlState.Normal)
This is how I accomplished this:
class ViewController: UIViewController {
#IBOutlet weak var faceLabel: UILabel!
#IBOutlet weak var scoreLabel: UILabel!
#IBOutlet weak var topLeftAnswer: UIButton!
#IBOutlet weak var topRightAnswer: UIButton!
#IBOutlet weak var bottomLeftAnswer: UIButton!
#IBOutlet weak var bottomRightAnswer: UIButton!
var randomEmojiNum: UInt32 = arc4random_uniform(6) + 1
override func viewDidLoad() {
super.viewDidLoad()
faceLabel.text = genRanNum()
correctAnswerGen()
}
func genRanNum() -> String{
switch randomEmojiNum{
case 1: return "😀"
case 2: return "😅"
case 3: return "😉"
case 4: return "😁"
case 5: return "😂"
case 6: return "😄"
default: break
}
return "Default"
}
func correctAnswerGen() {
var correct: UInt32 = arc4random_uniform(4)
switch correct{
case 0: topLeftAnswer.setTitle(genRanNum(), forState: UIControlState.Normal)
case 1: topRightAnswer.setTitle(genRanNum(), forState: UIControlState.Normal)
case 2: bottomLeftAnswer.setTitle(genRanNum(), forState: UIControlState.Normal)
case 3: bottomRightAnswer.setTitle(genRanNum(), forState: UIControlState.Normal)
default: break
}
}
}
Update : Edited According to OP requirement.

Resources