Adding thousands separators to UILabel numbers - ios

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?

Related

Cannot use instance member 'userCard1' within property initializer; property initializers run before 'self' is available error [duplicate]

This question already has answers here:
How to initialize properties that depend on each other
(4 answers)
Closed 2 years ago.
Trying to make a simple Blackjack app to get comfortable with using Xcode. I've never coded in Swift before and have a little experience in C++. Having an error I don't know how to fix. I'm having trouble applying other answers to similar questions to my situation.
I'm not totally sure what's causing the problem, let alone how to fix it :)
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
var balance = 500
let suits = ["h","d","c","s"]
//user card declarations
#IBOutlet weak var userCard1: UIImageView!
#IBOutlet weak var userCard2: UIImageView!
#IBOutlet weak var userCard3: UIImageView!
#IBOutlet weak var userCard4: UIImageView!
#IBOutlet weak var userCard5: UIImageView!
#IBOutlet weak var userCard6: UIImageView!
#IBOutlet weak var userCard7: UIImageView!
#IBOutlet weak var userCard8: UIImageView!
#IBOutlet weak var userCard9: UIImageView!
#IBOutlet weak var userCard10: UIImageView!
//dealer card declarations
#IBOutlet weak var dealerCard1: UIImageView!
#IBOutlet weak var dealerCard2: UIImageView!
#IBOutlet weak var dealerCard3: UIImageView!
#IBOutlet weak var dealerCard4: UIImageView!
#IBOutlet weak var dealerCard5: UIImageView!
var win = false
var bet = 0
//bet label
#IBOutlet weak var betLabel: UILabel!
//bet slider
#IBAction func betSlider(_ sender: UISlider) {
betLabel.text = String(Int(sender.value))
}
#IBOutlet weak var betSliderValue: UISlider!
var userCardSlot = 3
var dealerCardSlot = 3
var userTotal = 0
var dealerTotal = 0
//user cards displayed
var userCardArray = [userCard1, userCard2, userCard3, userCard4, userCard5, userCard6, userCard7, userCard8, userCard9, userCard10]
//dealer cards displayed
var dealerCardArray = [dealerCard1, dealerCard2, dealerCard3, dealerCard4, dealerCard5]
//hit button
#IBAction func hitTapped(_ sender: Any) {
var cardNum = Int.random(in: 2...14)
var cardSuit = Int(arc4random()) % 4
userCardArray[userCardSlot].image = UIImage(named: "\(cardSuit)card\(cardNum)")
}
//stand button
#IBAction func standTapped(_ sender: Any) {
for userTotal in userCardArray.reversed() {
userTotal += cardNum
}
for dealerTotal in dealerCardArray {
dealerTotal += cardNum
}
while dealerTotal < 17 {
dealerCardSlot += 1
dealerCardArray[dealerCardSlot].image = UIImage(named: "\(cardSuit)card\(cardNum)")
}
if dealerTotal <= userTotal {
win = true
} else {
win = false
}
}
#IBAction func newRoundTapped(_ sender: Any) {
bet = Int(betSliderValue.value)
userCardArray[0].image = UIImage(named: "\(cardSuit)card\(cardNum)")
userCardArray[1].image = UIImage(named: "\(cardSuit)card\(cardNum)")
dealerCardArray[0].image = UIImage(named: "\(cardSuit)card\(cardNum)")
dealerCardArray[0].image = UIImage(named: "Red_back.jpg")
//prompt for hit or stand
if win == true {
balance += (bet * 2)
} else {
balance -= bet
}
}
}
Any help's appreciated!
You generally cannot use one property to initialize another outside of init, because when you do:
var b = a + 1
the compiler implicitly does:
var b = self.a + 1
but self is not yet available; it's only available during the init.
The only exception is a lazy property initializer:
lazy var b: Int = self.a + 1
In your case, you can move the initialization into init:
var userCardArray: [UIImageView]
init() {
self.userCardArray = [userCard1, userCard2, ... ]
}

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

Why Does My App Crash due to Memory Issue?

I am dealing with an app created by some other developer. It's a complete app and has a lot of viewControllers , variables and outlets.
I keep getting the a crash after I load too many images from a server ( 200 for example ). I only get this message in the "print area" : "App terminated due to memory issue".
I use the library "SDWebImage" for loading the images. And I tried to find a memory leak using Instruments Allocations, and Leaks. I also used Memory Graph Debugger and non of them show leaks in my app.
Yet when I pop the View Controller ( DetailVC ) , it never fires the deinit method where I have put a message to print when this happens.
I have searched a lot to no vail. I have looked at these on Stackoverflow :
App Extension "Terminated due to memory issue"
App terminated due to memory issue
Through out my search I repeatedly see that response that the View Controller must be referenced by another view controller and this View Controller (DetailVC) strongly referencing the other.
I couldn't find that to be the case, although the file for the view controller is too large and I may have missed things.
It's difficult to go through the app and look for strong and weak references as the file is really huge.
is there a simple way ( or difficult for that matter ) to find the culprit and solve my problem.
Thanks
the code is huge (95000 characters) and contains sensitive information thus is not appropriate to post here. although I can post parts of it should you ask for it.
here is the code for DetailVC viewDidLoad :
import UIKit
import FTIndicator
import Cosmos
import Firebase
import MapKit
import YouTubePlayer
//MARK:- Gallery Collection Cell
class GalleryCollectionCell:UICollectionViewCell
{
#IBOutlet weak var imgViewShop: UIImageView!
override func awakeFromNib()
{
super.awakeFromNib()
}
}
//MARK:- Service Collection Cell
class ServiceCollectionCell:UICollectionViewCell
{
#IBOutlet weak var imgViewService: UIImageView!
#IBOutlet weak var lblService: UILabel!
override func awakeFromNib()
{
super.awakeFromNib()
}
}
#IBAction func btnBackAction(_ sender: Any)
{
self.navigationController?.popViewController(animated: true)
SDImageCache.shared().clearMemory()
SDImageCache.shared().clearDisk()
}
//MARK:- Detail Main Class
class DetailVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout,UITableViewDataSource, UITableViewDelegate,RateFinalDelegate, PhotoDicDelegate
{
//MARK:- Outlets
#IBOutlet weak var tblViewRate: UITableView!
#IBOutlet weak var tblViewService: UITableView!
#IBOutlet weak var lblServices: UILabel!
#IBOutlet weak var collViewGallery: UICollectionView!
//#IBOutlet weak var collViewService: UICollectionView!
#IBOutlet weak var constTableViewHeight: NSLayoutConstraint!
#IBOutlet weak var constTlbViewServiceHeight: NSLayoutConstraint!
#IBOutlet weak var imgViewShop: UIImageView!
#IBOutlet weak var lblShopName: UILabel!
//#IBOutlet weak var lblShopNameDetail: UILabel!
#IBOutlet weak var btnFavourites: UIButton!
#IBOutlet weak var viewStar: CosmosView!
#IBOutlet weak var lblReviewCount: UILabel!
#IBOutlet weak var btnShopStatus: UIButton!
#IBOutlet weak var lblShopOnline: UILabel!
// #IBOutlet weak var lblDetailText: UILabel!
#IBOutlet weak var btnShopRate: UIButton!
#IBOutlet weak var lblShopAddress: UILabel!
#IBOutlet weak var lblShopWebsite: UILabel!
#IBOutlet weak var lblShopView: UILabel!
#IBOutlet weak var lblShopOpenStatus: UILabel!
//#IBOutlet weak var lblPhone1: UILabel!
#IBOutlet weak var lblShopDetail: UILabel!
// #IBOutlet weak var btnFacebook: UIButton!
// #IBOutlet weak var btnSnapchat: UIButton!
// #IBOutlet weak var btnInstagram: UIButton!
// #IBOutlet weak var btnTwitter: UIButton!
// #IBOutlet weak var btnYoutube: UIButton!
// #IBOutlet weak var btnVivo: UIButton!
// #IBOutlet weak var btnGoogle: UIButton!
#IBOutlet weak var lblSat: UILabel!
#IBOutlet weak var lblSun: UILabel!
#IBOutlet weak var lblMon: UILabel!
#IBOutlet weak var lblTues: UILabel!
#IBOutlet weak var lblWed: UILabel!
#IBOutlet weak var lblThru: UILabel!
#IBOutlet weak var lblFri: UILabel!
#IBOutlet weak var lblSatText: UILabel!
#IBOutlet weak var lblSunText: UILabel!
#IBOutlet weak var lblMonText: UILabel!
#IBOutlet weak var lblTuesText: UILabel!
#IBOutlet weak var lblWedText: UILabel!
#IBOutlet weak var lblThruText: UILabel!
#IBOutlet weak var lblFriText: UILabel!
#IBOutlet weak var lblworkingHour: UILabel!
#IBOutlet weak var lblGallery: UILabel!
#IBOutlet weak var lblReviews: UILabel!
#IBOutlet weak var btnSeeMore: UIButton!
#IBOutlet weak var btnBack: UIButton!
#IBOutlet weak var viewMain: UIView!
#IBOutlet weak var viewSuper: UIView!
#IBOutlet weak var viewService: UIView!
#IBOutlet weak var btnWebsite: UIButton!
#IBOutlet weak var btnPhone1: UIButton!
#IBOutlet weak var btnPhone2: UIButton!
#IBOutlet weak var btnPhone3: UIButton!
#IBOutlet weak var constPhone1Height: NSLayoutConstraint!
#IBOutlet weak var constPhone2Height: NSLayoutConstraint!
#IBOutlet weak var constPhone3Height: NSLayoutConstraint!
#IBOutlet weak var constPhoneViewHeight: NSLayoutConstraint!
#IBOutlet weak var constViewScrollHeight: NSLayoutConstraint!
#IBOutlet weak var scrollSocial: UIScrollView!
// #IBOutlet weak var btnSocialLink: UIButton!
#IBOutlet weak var btnGallery: UIButton!
#IBOutlet weak var constViewServiceHeight: NSLayoutConstraint!
//For Photo Class
#IBOutlet weak var tblViewHeader: UITableView!
#IBOutlet weak var switchGallery: UISwitch!
#IBOutlet weak var constTableViewGalleryHeight: NSLayoutConstraint!
var albumListArray = [AlbumListData]()
//For Video Class
#IBOutlet weak var collectionViewVideos: UICollectionView!
#IBOutlet weak var constCollViewVideoHeight: NSLayoutConstraint!
var videoDataArray = [VideoListData]()
var switchStatus = Bool()
//MARK:- Variables
let globalConstants = GlobalConstants()
var UserData = UserDataValue()
var reviewDataArray = [Review]()
var galleryDataArray = [Gallery]()
var serviceDataArray = [Service]()
var ShopId = String()
var favStatus = String()
var ShopStatus = String()
var Latitude = String()
var Longitude = String()
var strFacebook = String()
var strInstagram = String()
var NotifyId = String()
var strTwitter = String()
var strSnapchat = String()
var strYoutube = String()
var strGoogle = String()
var strVimeo = String()
var chatStatus = Bool()
var isfirstTime = Bool()
var receiverId = ""
var receiverImage = ""
var receiverName = ""
var strWebsite = ""
var shopOwnerId = ""
var ShopUnqueId = ""
var HideChatStatus = ""
var IsChatCreateScreen = ""
var strPhone1Number = String()
var strPhone2Number = String()
var strPhone3Number = String()
var RateText = Bool()
var ShopDeliveryServiceItself = Bool()
var CitySelectedId = String()
var OneToOneChatUserData : NSDictionary = [:]
var ShopString = "1159,1160,1162,1166,1167,1176,1178,1179,1180,1182,1184,1185,1186,1187,1188,1189,1190,1191,1192,1193,1194,1199,1202,1203,1206,1208,1209,1210,1214,1216,1217,1218,1224,1225,1227,1230,1232,1233,1234,1235,1236,1238,1239,1240,1242,1243,1244,1245,1246,1247,1248,1250,1252,1253,1255,1258,1259,1263,1264,1265,1266,1269,1270,1272,1275,1276,1277,1278,1279,1280,1281,1282,1283,1285,1298,1299,1302";
//MARK:- View Life Cycle
override func viewDidLoad()
{
super.viewDidLoad()
// collViewGallery.dataSource = self
// collViewGallery.delegate = self
// collViewService.dataSource = self
// collViewService.delegate = self
btnShopStatus.setTitle(" CHAT".localiz(), for: .normal)
btnSeeMore.setTitle("See More".localiz(), for: .normal)
btnShopRate.setTitle("RATE".localiz(), for: .normal)
btnGallery.setTitle("Gallery".localiz(), for: .normal)
lblworkingHour.text = "Working Hours:".localiz()
lblServices.text = "Services".localiz()
lblGallery.text = "Gallery".localiz()
lblReviews.text = "REVIEWS".localiz()
//lblDetailText.text = "DETAILS".localiz()
lblSatText.text = "Saturday".localiz()
lblSunText.text = "Sunday".localiz()
lblMonText.text = "Monday".localiz()
lblTuesText.text = "Tuesday".localiz()
lblWedText.text = "Wednesday".localiz()
lblThruText.text = "Thursday".localiz()
lblFriText.text = "Friday".localiz()
viewStar.settings.fillMode = .precise
self.navigationItem.title = globalConstants.detailText
tblViewRate.register(UINib(nibName: "RateTableVCell", bundle: nil), forCellReuseIdentifier: "RateTableVCell")
tblViewService.register(UINib(nibName: "ServiceTableCell", bundle: nil), forCellReuseIdentifier: "ServiceTableCell")
tblViewHeader.register(UINib(nibName: "SubCatHeaderTVC", bundle: nil), forCellReuseIdentifier: "SubCatHeaderTVC")
tblViewHeader.dataSource = self
tblViewHeader.delegate = self
tblViewHeader.estimatedRowHeight = 120
tblViewHeader.rowHeight = UITableViewAutomaticDimension
tblViewService.dataSource = self
tblViewService.delegate = self
tblViewService.estimatedRowHeight = 50
tblViewService.rowHeight = UITableViewAutomaticDimension
self.constTlbViewServiceHeight.constant = 20
collectionViewVideos.register(UINib(nibName: "VideoCollViewCell", bundle: nil), forCellWithReuseIdentifier: "VideoCollViewCell")
collectionViewVideos.dataSource = self
collectionViewVideos.delegate = self
collectionViewVideos.reloadData()
switchStatus = false
switchGallery.setOn(false, animated: true)
//self.constViewServiceHeight.constant = 20
tblViewRate.dataSource = self
tblViewRate.delegate = self
tblViewRate.estimatedRowHeight = 100
tblViewRate.rowHeight = UITableViewAutomaticDimension
//self.constTableViewGalleryHeight.constant = 20
self.constTableViewHeight.constant = 20
// self.tblViewHeader.isHidden = false
// self.collectionViewVideos.isHidden = true
// self.constCollectionViewHeight.constant = 30
ShopStatus = ""
self.addBackButton()
UserDefaults.standard.set(ShopId, forKey: "ShopValueId")
UserDefaults.standard.synchronize()
isfirstTime = true
viewSuper.backgroundColor = UIColor.lightGray
viewMain.isHidden = true
if LanguageManger.shared.currentLanguage == .en
{
lblServices.textAlignment = .left
btnBack.setImage(UIImage(named:"back"), for: .normal)
}
else
{
lblServices.textAlignment = .right
btnBack.setImage(UIImage(named:"ReverseBack"), for: .normal)
}
// if KAppDelegate.isUserLoggedIn()
// {
// let userDic = UserDefaults.standard.value(forKey: "UserData") as! [String:Any]
// self.UserData = UserDataValue.init(fromDictionary: userDic)
// UserId = self.UserData.id!
// UserName = self.UserData.name!
// }
if KAppDelegate.isUserLoggedIn()
{
let userDic = UserDefaults.standard.value(forKey: "UserData") as! [String:Any]
self.UserData = UserDataValue.init(fromDictionary: userDic)
CitySelectedId = self.UserData.city!
}
else
{
if UserDefaults.standard.value(forKey: "CitySelectedId") != nil
{
CitySelectedId = UserDefaults.standard.value(forKey: "CitySelectedId") as! String
}
else
{
CitySelectedId = "1"
}
}
ShopDetailAPIMethod()
}
override func viewWillAppear(_ animated: Bool)
{
self.navigationController?.navigationBar.isHidden = true
}
override func viewWillDisappear(_ animated: Bool)
{
self.IsChatCreateScreen = ""
self.navigationController?.navigationBar.isHidden = false
}
// override var preferredStatusBarStyle: UIStatusBarStyle
// {
// return .default
// }
//MARK:- Photo Dic Delegate Method
//MARK:- CreateNewChat Method
}
and this is how instantiate the DetailVC :
#objc func methodOfNotification(notification: Notification)
{
if UserDefaults.standard.value(forKey: "ShopValueId") != nil
{
let detailVC = self.storyboard?.instantiateViewController(withIdentifier: "DetailVC") as! DetailVC
detailVC.ShopId = UserDefaults.standard.value(forKey: "ShopValueId") as! String
self.navigationController?.pushViewController(detailVC, animated: true)
}
}
Here is the scenario:
I am within subCategoryVC I click on a collectionView cell, this instantiates the DetailVC. within the DetailVC I click on the seeAll button to load the images in the collection view ( this is done using SDWebImage using this method :
l
let imageStringURL = ShopDetailData.coverImage!
imgViewShop.sd_setShowActivityIndicatorView(true)
imgViewShop.sd_setIndicatorStyle(.gray)
imgViewShop.sd_setImage(with: NSURL(string:imageStringURL)! as URL, placeholderImage:UIImage(named:"noimage") , options: .refreshCached, completed: nil)
when I click on the btnBack(back button) and I pop the view controller using navigationContrller.popViewController() this is where the deinit message should be printed in the "print area" but this never happens.
furthermore when I open 2 or 3 detailVC's and push the seeAll button the app crashes and "print area" shows
"app terminated due to memory issue".
I just used Instruments to check for memory leak. there is one leak as it turns out and with these details :
leaked object = _swiftStringStorage<UInt16>
responsible library = libswiftCore.dylib
responsible frame = swift_slowAlloc
The Apps allows limited memory. I guess after 800mb , app is shut down with memory issue. This is not a true way that is downloaded 200 images for one controller but you can use with tableview with dequereuaseble and sdwebimage or kingfisher. Also you can use thumbnail images because you dont need to show 1 mb image in imageview , this is not unnecessary.
You probably have a retain-cycle. This means that some of the subviews of your ViewController has a strong reference to the ViewController itself or to another object that has the strong reference to the ViewController. When this happens, even if you pop the ViewController it won't be destroyed until the subview is destroyed, which will never be destroyed while the ViewController exists.
If this is your case, the solution would be searching for this circular reference in your subviews and put a "weak" in the variable that references the ViewController. Searching for places where you assign "self" to a variable or where you use "self" inside an enclosure could help.

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 can I increment a label by pressing a button that is in a separate view?

so basically I'm familiar with app development and Xcode, but I'm still in the beginning stages of learning and I need some help. I've created a emotions quiz type UI and at the end of the 10 questions, I have a page that displays the different emotions and the scores that the user earned throughout the quiz. What I need help on is wen the user clicks a button on question 1 to get the label on my results page to increase by 1. I've tried many different methods so far but can't seem to quite figure it out. Ive linked my buttons to their respective view controller as actions and the labels to their respective view controller as outlets.
import UIKit
class Question1: UIViewController {
#IBAction func buttonlightgreen(_ sender: UIButton) {
print ("light green")
sadscoreText += 1
}
#IBAction func buttonred(_ sender: Any) {
print ("red")
angryscoreText += 2
happyscoreText += 1
}
#IBAction func buttonpurple(_ sender: Any) {
print ("purple")
annoyedscoreText += 1
stressedscoreText += 1
}
#IBAction func buttondarkgreen(_ sender: Any) {
print ("dark green")
relaxedscoreText += 2
tiredscoreText += 1
}
#IBAction func buttonyellow(_ sender: Any) {
print ("yellow")
happyscoreText += 1
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
That is the code for the buttons and this is the code for the labels.
import UIKit
var sadscoreText = 0
var happyscoreText = 0
var relaxedscoreText = 0
var angryscoreText = 0
var annoyedscoreText = 0
var tiredscoreText = 0
var stressedscoreText = 0
class Results: UIViewController {
#IBOutlet weak var sadscore: UILabel!
#IBOutlet weak var happyscore: UILabel!
#IBOutlet weak var relaxedscore: UILabel!
#IBOutlet weak var angryscore: UILabel!
#IBOutlet weak var annoyedscore: UILabel!
#IBOutlet weak var tiredscore: UILabel!
#IBOutlet weak var stressedscore: UILabel!
var sadscoreText: Int = 0 {
didSet {
sadscore.text = "\(sadscoreText)"
}
}
override func viewDidLoad() {
super.viewDidLoad()
sadscoreText = 0
happyscoreText = 0
relaxedscoreText = 0
angryscoreText = 0
annoyedscoreText = 0
tiredscoreText = 0
stressedscoreText = 0
}
}
I believe the reason its not working is because you are assigning 0 to the values before assigning the modified values to label in viewDidLoad method. You can achieve the required behaviour like this:
Modify your Results view controller as follows:
import UIKit
var sadscoreText = 0
var happyscoreText = 0
var relaxedscoreText = 0
var angryscoreText = 0
var annoyedscoreText = 0
var tiredscoreText = 0
var stressedscoreText = 0
class Results: UIViewController {
#IBOutlet weak var sadscore: UILabel!
#IBOutlet weak var happyscore: UILabel!
#IBOutlet weak var relaxedscore: UILabel!
#IBOutlet weak var angryscore: UILabel!
#IBOutlet weak var annoyedscore: UILabel!
#IBOutlet weak var tiredscore: UILabel!
#IBOutlet weak var stressedscore: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
sadscore.text = "\(sadscoreText)"
happyscore.text = "\(happyscoreText)"
//follow the same for other labels
//you can set the values again to zero after showing the labels on the screen like this
sadscoreText = 0
happyscoreText = 0
}
}

Resources