increment/decrement the value of a label with two buttons - swift

being new of swift means that I have issues with two buttons to increment the value of a label.I'm stuck because the increment button works but the decrement button doesn't. the value that I want to store inside the label decrease but the label doesn't update. here's the code, thank you
PS: all those isEnabled = true or false are only to disable the buttons to be able create a range from 0 to 5
class ViewController: UIViewController {
var incDec = 0;
#IBOutlet weak var countLbl: UILabel!
#IBOutlet weak var decBtn: UIButton!
#IBOutlet weak var incBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func tapDec(_ sender: Any) {
if(incDec >= -1){
incDec -= 1;
self.countLbl.text = "\(incDec)"
decBtn.isEnabled = true
}
else{
self.countLbl.text = "\(incDec)"
decBtn.isEnabled = false
incBtn.isEnabled = true
}
}
#IBAction func tapInc(_ sender: Any) {
if(incDecVal < 5){
incDec += 1;
self.countLbl.text = "\(incDec)"
incBtn.isEnabled = true
}
else{
self.countLbl.text = "\(incDec)"
incBtn.isEnabled = false
decBtn.isEnabled = true
}
}
}

You have to modify the logic of enabling and disabling the buttons. Here is the code.
class ViewController: UIViewController {
var incDecVal = 0;
#IBOutlet weak var countLbl: UILabel!
#IBOutlet weak var decBtn: UIButton!
#IBOutlet weak var incBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
countLbl.text = "\(incDecVal)"
}
#IBAction func tapDec(_ sender: Any) {
if(incDecVal > 0){
incDecVal = incDecVal - 1;
}
decBtn.isEnabled = incDecVal == 0 ? false : true
incBtn.isEnabled = true
self.countLbl.text = "\(incDecVal)"
}
#IBAction func tapInc(_ sender: Any) {
if(incDecVal <= 5) {
incDecVal = incDecVal + 1;
}
incBtn.isEnabled = incDecVal == 5 ? false : true
decBtn.isEnabled = true
self.countLbl.text = "\(incDecVal)"
}
}

Related

What does this error "Thread 1: EXC_BAD_ACCESS (code=2, address=0x30d51fff8)" mean? How do I fix it

import UIKit
class ViewController: UIViewController {
#IBOutlet weak var triviaLabel: UILabel!
#IBOutlet weak var trueButton: UIButton!
#IBOutlet weak var falseButton: UIButton!
#IBOutlet weak var progressBar: UIProgressView!
var quiz = [Question(text: "Blah blah", answer: "True"),
Question(text: "Ha ha", answer: "True"),Question(text: "Bruh bruh", answer: "False")]
var questionNumber = 0
override func viewDidLoad() {
super.viewDidLoad()
updateQuestion()
}
#IBAction func answerButtonPressed(_ sender: UIButton) {
let userAnswer = sender.currentTitle
let actualAnswer = quiz[questionNumber].answer
if userAnswer == actualAnswer {
} else {
}
if questionNumber < quiz.count-1 {
questionNumber += 1
}else {
questionNumber = 0
}
updateQuestion()
}
func updateQuestion() {
triviaLabel.text = quiz[questionNumber].text // Get the error here
updateQuestion()
}
}
The build succeeds and the app launches but there comes a blank screen and the error occurs. I tried mapping the label again with the storyboard. I speculate that there is some problem with the label declaration or connection.

Swift: Why can I pass info from one IBAction to another, but not to a function

I am trying to get the values for splitValue and tipPercent into the getSettings() at the bottom. Why can I get the values for both of those in the IBAction calculatePressed, but when I try to get the values into the function the value is nil. I am sooo confused. Thank you for the help!
#IBOutlet weak var billTextField: UITextField!
#IBOutlet weak var zeroPctButton: UIButton!
#IBOutlet weak var tenPctButton: UIButton!
#IBOutlet weak var twentyPctButton: UIButton!
#IBOutlet weak var splitNumberLabel: UILabel!
var tipChosen = ""
var totalPerPerson = ""
var tipPercent = ""
var splitValue = ""
#IBAction func tipChanged(_ sender: UIButton) {
tipPercent = sender.currentTitle!
if sender.isSelected == true {
return
}
zeroPctButton.isSelected = false
tenPctButton.isSelected = false
twentyPctButton.isSelected = false
sender.isSelected = true
if sender.currentTitle == "0%" {
tipChosen = "0.00"
} else if sender.currentTitle == "10%" {
tipChosen = "0.10"
} else if sender.currentTitle == "20%" {
tipChosen = "0.20"
}
billTextField.endEditing(true)
}
#IBAction func stepperValueChanged(_ sender: UIStepper) {
splitValue = String(Int(sender.value))
splitNumberLabel.text = String(Int(sender.value))
}
#IBAction func calculatePressed(_ sender: UIButton) {
let bill = Float(billTextField.text!)!
let tip = Float(tipChosen)!
let tax = bill * tip
let splitNumber = Float(splitNumberLabel.text!)
let total = (bill + tax) / Float(splitNumber!)
totalPerPerson = "$\(String(format: "%.2f", total))"
performSegue(withIdentifier: "goToTotal", sender: self)
}
func getSettings() -> String {
return "Split between \(splitValue) people, with a \(tipPercent) tip."
}
Ok, sorry it took me a bit, but I finally think I understand what I did.
class CalculatorViewController: UIViewController {
var tip = 0.0
var finalBill = ""
var split = 2
#IBOutlet weak var billTextField: UITextField!
#IBOutlet weak var zeroPctButton: UIButton!
#IBOutlet weak var tenPctButton: UIButton!
#IBOutlet weak var twentyPctButton: UIButton!
#IBOutlet weak var splitNumberLabel: UILabel!
#IBAction func tipChanged(_ sender: UIButton) {
if sender.isSelected == false {
sender.isSelected = false
} else if sender.isSelected == true {
sender.isSelected = true
}
zeroPctButton.isSelected = false
tenPctButton.isSelected = false
twentyPctButton.isSelected = false
sender.isSelected = true
billTextField.endEditing(true)
}
#IBAction func stepperValueChanged(_ sender: UIStepper) {
splitNumberLabel.text = Int(sender.value).description
}
#IBAction func calculatePressed(_ sender: UIButton) {
if zeroPctButton.isSelected == true {
tip = 0.0
} else if tenPctButton.isSelected == true {
tip = 0.1
} else if twentyPctButton.isSelected == true {
tip = 0.2
}
print(tip)
let bill = Double(billTextField.text!)
split = Int(Double(splitNumberLabel.text!)!)
if billTextField.text != "" {
let billWithTip = (bill! * tip) + bill!
let billWithTipSplit = billWithTip / Double(split)
finalBill = String(format: "%.2f", billWithTipSplit)
print(billWithTip)
}
self.performSegue(withIdentifier: "getResults", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "getResults" {
let destinationVC = segue.destination as! ResultsViewController
destinationVC.finalBill = finalBill
destinationVC.split = split
destinationVC.tip = tip
}
}
}
class ResultsViewController: UIViewController {
#IBOutlet weak var totalLabel: UILabel!
#IBOutlet weak var settingsLabel: UILabel!
var tip = 0.0
var split = 2
var finalBill = ""
override func viewDidLoad() {
super.viewDidLoad()
totalLabel.text = "$\(finalBill)"
settingsLabel.text = "Split between \(Int(split)) people, with a \(Int(tip * 100))% tip"
}
#IBAction func recalculatePressed(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
I did what you suggested with the string and some minor calculations on the second view controller, changed the values of a few declared properties and got rid of the getSettings(). I was under the impression that I couldn't pass data without a return value from a function. Thank you for the help!

If i put UIView B on UIView A and hide/show them by using Segmented Control is it Professional way?

I am trying to handle UIViews hide/show by using (isHidden) UISegmented Control is it professional way how can i handle this.
#IBOutlet weak var flightTypeSegCont: UISegmentedControl!
#IBAction func flightType(_ sender: UISegmentedControl) {
if(flightTypeSegCont.selectedSegmentIndex == 0)
{
self.direcrCard.isHidden = false
self.ViaCardView.isHidden = true
}
else
{
self.direcrCard.isHidden = true
self.ViaCardView.isHidden = false
}
}
You can do it like that:
#IBOutlet weak var flightTypeSegCont: UISegmentedControl!
#IBAction func flightType(_ sender: UISegmentedControl) {
let shouldHide = flightTypeSegCont.selectedSegmentIndex == 0
self.direcrCard.isHidden = !shouldHide
self.ViaCardView.isHidden = shouldHide
}

Bug Problems With Swift and XCode

Help, I am coding this game, and I keep getting an error that says:
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
Example:
Everything has worked normally until I added code for the trump coin image and the label that says 'Score:'
import UIKit
class ViewController: UIViewController {
//DEFINING VARIABLES
var gameIsRunning = false
var paused = false
var totalCoins = 0
var totalScore = 0
var gameCoins = 0
var gameScore = 0
#IBOutlet var titleCoinsLabel: UILabel!
#IBOutlet var titleScoreLabel: UILabel!
#IBOutlet var titleTrumpCoin: UIImageView!
#IBOutlet var titleScoreRun: UILabel!
#IBOutlet var gameTitle: UILabel!
#IBOutlet var playButton: UIButton!
#IBOutlet var pauseButton: UIButton!
#IBOutlet var pauseView: UIView!
#IBOutlet var resumeButton: UIButton!
#IBOutlet var optionsButton: UIButton!
#IBOutlet var tutorialButton: UIButton!
#IBOutlet var rateApp: UIButton!
#IBOutlet var quitButton: UIButton!
#IBOutlet var tutorialBackButton: UIButton!
#IBOutlet var tutorialView: UIView!
#IBOutlet var titleOptions: UIButton!
#IBOutlet var titleTutorial: UIButton!
#IBOutlet var optionsView: UIView!
#IBOutlet var optionsBack: UIButton!
//WHEN GAME LOADS WHAT TO DO
override func viewDidLoad() {
super.viewDidLoad()
gameIsRunning = false
pauseButton.isHidden = true
pauseButton.isEnabled = false
pauseButton.layer.cornerRadius = 10
pauseButton.alpha = 0.75
pauseView.isHidden = true
pauseView.layer.cornerRadius = 20
tutorialView.isHidden = true
resumeButton.layer.cornerRadius = 8
optionsButton.layer.cornerRadius = 8
tutorialButton.layer.cornerRadius = 8
rateApp.layer.cornerRadius = 8
quitButton.layer.cornerRadius = 8
tutorialBackButton.layer.cornerRadius = 8
optionsView.layer.cornerRadius = 20
optionsBack.layer.cornerRadius = 8
optionsView.isHidden = true
titleCoinsLabel.text = String(totalCoins)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//STARTING GAME
#IBAction func startGame(_ sender: AnyObject) {
if gameIsRunning == false {
gameIsRunning = true
titleCoinsLabel.isHidden = true
titleScoreLabel.isHidden = true
playButton.isHidden = true
playButton.isEnabled = false
gameTitle.isHidden = true
gameTitle.isEnabled = false
pauseButton.isHidden = false
pauseButton.isEnabled = true
titleTutorial.isHidden = true
titleTutorial.isEnabled = false
titleOptions.isHidden = true
titleOptions.isEnabled = false
titleScoreRun.isHidden = true
titleTrumpCoin.isHidden = true
//NOT DEFINED YET
runGame()
}
}
//PAUSE
#IBAction func pauseGame(_ sender: AnyObject) {
paused = true
pauseView.isHidden = false
}
//RESUME
#IBAction func resumeGame(_ sender: AnyObject) {
paused = false
pauseView.isHidden = true
}
//VIEW OPTIONS
#IBAction func optionsView(_ sender: AnyObject) {
optionsView.isHidden = false
pauseView.isHidden = true
}
#IBAction func titleOptionsView(_ sender: AnyObject) {
optionsView.isHidden = false
}
//BACK FROM OPTIONS
#IBAction func optionsBack(_ sender: AnyObject) {
optionsView.isHidden = true
if (paused == true) {
pauseView.isHidden = false
} else {
pauseView.isHidden = true
}
}
//OPTIONS TWEAKS
#IBAction func gameVolumeSlider(_ sender: AnyObject) {
}
#IBAction func musicVolumeSlider(_ sender: AnyObject) {
}
//VIEW TUTORIAL
#IBAction func tutorialView(_ sender: AnyObject) {
pauseView.isHidden = true
tutorialView.isHidden = false
}
#IBAction func titleTutorial(_ sender: AnyObject) {
tutorialView.isHidden = false
}
//BACK FROM TUTORIAL
#IBAction func backTutorial(_ sender: AnyObject) {
tutorialView.isHidden = true
if (paused == true) {
pauseView.isHidden = false
} else {
pauseView.isHidden = true
}
}
//RATE APP
#IBAction func rateApp(_ sender: AnyObject) {
}
//QUIT GAME
#IBAction func quitGame(_ sender: AnyObject) {
titleScoreLabel.isHidden = false
titleCoinsLabel.isHidden = false
pauseButton.isHidden = true
pauseView.isHidden = true
gameTitle.isHidden = false
gameTitle.isEnabled = true
playButton.isHidden = false
playButton.isEnabled = true
titleTutorial.isHidden = false
titleTutorial.isEnabled = true
titleOptions.isHidden = false
titleOptions.isEnabled = true
titleScoreRun.isHidden = true
titleScoreRun.isHidden = false
titleTrumpCoin.isHidden = false
titleScoreLabel.text = String(gameScore)
titleCoinsLabel.text = String(totalCoins)
totalScore = totalScore + gameScore
gameScore = 0
totalCoins = totalCoins + gameCoins
gameCoins = 0
}
//RECOGNIZING SWIPES
#IBAction func swipeRight(_ sender: AnyObject) {
if (gameIsRunning == true) {
}
}
#IBAction func swipeLeft(_ sender: AnyObject) {
if (gameIsRunning == true) {
}
}
#IBAction func press(_ sender: AnyObject) {
}
//FUNCTIONS TO RUN GAME
func runGame() {
}
}
It would appear that you have not hooked up the titleScoreLabel outlet correctly. Double check that in Interface Builder.

Applying an NSTimer to a UILabel (Swift)

i'm quite new to using swift and i'm currently working on a small school project. However, one function i cant seem to work out is how to make an NSTimer change the text in a UILabel after a certain amount of time. I want to apply this function to a UILabel (cannotbuy) that was blank, and had just been changed to text displaying a message("you dont have enough points"), and i want this message to be removed and the UILabel to be blank again after a second or so. Can anyone help me? Thanks.
class Upgrades: UIViewController{
#IBOutlet weak var shprogresslabel: UILabel!
#IBOutlet weak var fsprogresslabel: UILabel!
#IBOutlet weak var shprogress: UIProgressView!
#IBOutlet weak var fsprogress: UIProgressView!
#IBOutlet weak var shbutton: UIButton!
#IBOutlet weak var fsbutton: UIButton!
#IBOutlet weak var storepoints: UILabel!
#IBOutlet weak var cannotbuy: UILabel!
#IBOutlet weak var label2: UILabel!
#IBOutlet weak var label1: UILabel!
var fsprice = Int()
var shprice = Int()
let defaults = NSUserDefaults.standardUserDefaults()
func updateProgress1(){
fsprogress.progress += 0.1
let fsprogressvalue = self.fsprogress.progress
fsprogresslabel.text = "\(fsprogressvalue * 100)%"
}
func updateProgress2(){
shprogress.progress += 0.2
let shprogressvalue = self.shprogress.progress
shprogresslabel.text = "\(shprogressvalue * 100)%"
}
#IBAction func button2(sender: AnyObject) {
if shprice <= 90{
if SharingManager.sharedInstance.totalscore >= shprice{
SharingManager.sharedInstance.shiphealth = SharingManager.sharedInstance.shiphealth + 1
SharingManager.sharedInstance.totalscore = SharingManager.sharedInstance.totalscore - fsprice
storepoints.text = String(SharingManager.sharedInstance.totalscore)
shprice = shprice + 20
print(shprice)
label2.text = ("\(shprice)")
defaults.setInteger(SharingManager.sharedInstance.shiphealth, forKey: "SharingManager.sharedInstance.shiphealth")
updateProgress2()
}else{
cannotbuy.text = "You dont have enough points"
}
}else{
cannotbuy.text = "You have purchased all the available upgrades for this"
}
}
#IBAction func button1(sender: AnyObject) {
if fsprice <= 100{
if SharingManager.sharedInstance.totalscore >= fsprice{
SharingManager.sharedInstance.bulletspeed = SharingManager.sharedInstance.bulletspeed - 0.15
SharingManager.sharedInstance.totalscore = SharingManager.sharedInstance.totalscore - fsprice
storepoints.text = String(SharingManager.sharedInstance.totalscore)
fsprice = fsprice + 10
print(fsprice)
label1.text = ("\(fsprice)")
defaults.setDouble(SharingManager.sharedInstance.bulletspeed, forKey: "SharingManager.sharedInstance.bulletspeed")
updateProgress1()
}else{
cannotbuy.text = "You dont have enough points"
}
}else{
cannotbuy.text = "You have purchased all the available upgrades for this"
}
}
override func viewDidLoad() {
if fsprice == 0{
fsprice = 10
}
if shprice == 0{
shprice = 10
}
if fsprice == 180{
fsbutton.enabled = false
}
if shprice == 100{
shbutton.enabled = false
}
storepoints.text = String(SharingManager.sharedInstance.totalscore)
label1.text = ("\(fsprice)")
label2.text = ("\(shprice)")
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
There are two ways for you to do this:
Using NSTimer:
#IBAction func button2(sender: AnyObject) {
...
cannotbuy.text = "You don't have enough points"
NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: #selector(ViewController.resetCannotBuy), userInfo: nil, repeats: false)
}
func resetCannotBuy() {
cannotbuy.text = ""
}
Using dispatch_after:
#IBAction func button2(sender: AnyObject) {
...
cannotbuy.text = "You don't have enough points"
let fiveSecondLater = dispatch_time(DISPATCH_TIME_NOW, 5 * Int64(NSEC_PER_SEC))
dispatch_after(fiveSecondLater, dispatch_get_main_queue()) {
self.cannotbuy.text = ""
}
}
NSEC_PER_SEC is the constant for nanosecond per second, which is equal to 1 billion.