Swift - Printing out the current value of a number - ios

I'm currently developing a counter app which every time you press a button it will count up. I have already done this and works 100%, what I'm trying to do is make a another button and when you press it, it shows the current number on the console but it only prints out 0 because that's the default variable I assigned the value to.
My whole class:
var counterNumber = 0
#IBOutlet weak var counterLabel: UILabel!
func initCount(){
counterNumber = 0
}
func numberUp(){
self.counterNumber++;
counterLabel.text = "\(self.counterNumber)"
}
#IBAction func CountUp(sender: UIButton) {
numberUp()
}
#IBAction func RestartButton(sender: UIButton) {
initCount()
}
#IBAction func printButton(sender: UIButton) {
self.numberUp();
print(self.counterNumber)
}
override func viewDidLoad() {
super.viewDidLoad()
initCount()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

Just call method numberUp in printButton: action.
var counterNumber = 0//this is a variable of class
#IBOutlet weak var counterLabel: UILabel!
#IBAction func printButton(sender: UIButton) {
self.numberUp();
print(self.counterNumber)
}
func numberUp(){
self.counterNumber++;
counterLabel.text = "\(self.counterNumber)"
}

Use 'self' keyword to call instance variables.
class ViewController: UIViewController {
// Properties
var counterNumber:Int = 0 // Make this variable Global to Class
// IBOutlets Properties
#IBOutlet weak var counterLabel: UILabel!
#IBAction func printButton(sender: UIButton) {
self.numberUp()
self.counterLabel.text = "\(self.counterNumber)"
print("\n You Pressed ==> \(sender.title) button \(self.counterNumber) times")
}
func numberUp() {
self.counterNumber += 1
self.counterLabel.text = "\(counterNumber)"
}
}

Related

why my stepper does't give the correct value when I tap the increment button?

I am using kw stepper pod, since it is customizable. I can separate the increment button, decrement button and using my own label. but the behaviour should be the same as UIStepper
that is what it looks like, it consists of 1 increment button, 1 decrement button and counter label.
here is the code on my view controller:
import UIKit
import KWStepper
class ViewController: UIViewController {
#IBOutlet weak var counterLabel: UILabel!
#IBOutlet weak var decrementButton: UIButton!
#IBOutlet weak var incrementButton: UIButton!
var stepper: KWStepper!
override func viewDidLoad() {
super.viewDidLoad()
stepper = KWStepper(decrementButton: decrementButton, incrementButton: incrementButton)
stepper.autoRepeat = false
stepper.autoRepeatInterval = 1
stepper.wraps = false
stepper.minimumValue = 0
stepper.maximumValue = 100
stepper.incrementStepValue = 1
stepper.decrementStepValue = 1
stepper.value = 0.0
counterLabel.text = "\(stepper.value)"
}
#IBAction func incrementButtonDidTapped(_ sender: Any) {
counterLabel.text = "\(stepper.value)"
}
#IBAction func decrementButtonDidTapped(_ sender: Any) {
counterLabel.text = "\(stepper.value)"
}
}
I connect the increment and decrement button using #IBAction touch up inside event.
so I expect when I tap the increment button, it will increase from
0,0 -> 1.0 -> 2.0 -> 3.0 and so on.
but in my case, when tap the increment button it will give
0,0 -> 0,0 -> 1,0 -> 2,0
the 0,0 will appear twice. why it appears twice ? how to solve this issue
I know that I can see the stepper value from value change event like this
stepper
.valueChanged { stepper in
// ...
}
but I need to separate the event from increment and decrement button
here is the project on my google drive: https://drive.google.com/file/d/1IgeVW1OemRttoAOqJ6Ba8LpyZC_rc3-o/view?usp=sharing
The incrementButtonDidTapped and decrementButtonDidTapped methods are possibly being called before stepper.value changes, since KWStepper also listens for touchUpInside events from both of these buttons to change its value.
KWStepper exposes two properties decrementCallback and incrementCallback which you can use to get notified when the value gets decremented/incremented. You can use these instead of an IBAction on the two buttons.
stepper.decrementCallback = { (stepper) in
self.counterLabel.text = "\(stepper.value)"
}
stepper.incrementCallback = { (stepper) in
self.counterLabel.text = "\(stepper.value)"
}
Alternatively, you can confirm to KWStepperDelegate and implement KWStepperDidIncrement and KWStepperDidDecrement delegate methods to get notified.
import UIKit
import KWStepper
class ViewController: UIViewController, KWStepperDelegate {
#IBOutlet weak var counterLabel: UILabel!
#IBOutlet weak var decrementButton: UIButton!
#IBOutlet weak var incrementButton: UIButton!
var stepper: KWStepper!
override func viewDidLoad() {
super.viewDidLoad()
stepper = KWStepper(decrementButton: decrementButton, incrementButton: incrementButton)
stepper.autoRepeat = false
stepper.autoRepeatInterval = 1
stepper.wraps = false
stepper.minimumValue = 0
stepper.maximumValue = 100
stepper.incrementStepValue = 1
stepper.decrementStepValue = 1
stepper.value = 0.0
// Set the delegate
stepper.delegate = self
counterLabel.text = "\(stepper.value)"
}
#objc func KWStepperDidIncrement() {
counterLabel.text = "\(stepper.value)"
}
#objc func KWStepperDidDecrement() {
counterLabel.text = "\(stepper.value)"
}
}
You can replace your click events with following code
#IBAction func incrementButtonDidTapped(_ sender: Any) {
stepper.valueChanged { (steper) in
self.counterLabel.text = "\(steper.value)"
}
}
#IBAction func decrementButtonDidTapped(_ sender: Any) {
stepper.valueChanged { (steper) in
self.counterLabel.text = "\(steper.value)"
}
}

Is hidden not working on image views in Swift 3?

#IBOutlet weak var allStocksSelected: UIImageView!
#IBOutlet weak var shortStocksSelected: UIImageView!
#IBOutlet weak var longStocksSelected: UIImageView!
#IBOutlet weak var myStocksTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
myStocksTableView.delegate = self
myStocksTableView.dataSource = self
}
override func viewDidAppear(_ animated: Bool) {
self.shortStocksSelected.isHidden = true
self.longStocksSelected.isHidden = true
self.allStocksSelected.isHidden = true
}
#IBAction func allStocksButtonPressed(_ sender: Any) {
print("ALL!")
self.stockTypeChanged(stockType: allStocksSelected)
}
#IBAction func shortStocksButtonPressed(_ sender: Any) {
print("SHORT!")
self.stockTypeChanged(stockType: shortStocksSelected)
}
#IBAction func longStocksButtonPressed(_ sender: Any) {
print("LONG!")
self.longStocksSelected.isHidden = false
self.shortStocksSelected.isHidden = true
self.allStocksSelected.isHidden = true
//stockTypeChanged(stockType: longStocksSelected)
}
#IBAction func addNewStockButtonPressed(_ sender: Any) {
}
#IBAction func signOutButtonPressed(_ sender: Any) {
}
private func stockTypeChanged(stockType: UIImageView) {
let stockTypes: [UIImageView] = [allStocksSelected, shortStocksSelected, longStocksSelected]
for (stock) in stockTypes {
if (stock == stockType) {
stock.isHidden = false
} else {
stock.isHidden = true
}
}
}
As shown from my code above, I am basically just trying to hide and show certain image views when buttons are pressed.
I am 100% sure that all of the buttons actions and IB outlets are properly connected, yet the image views are still not hiding and showing, and I cannot figure out why.
I was running into this same issue. Placing your isHidden code to execute on the main thread should solve the problem.
DispatchQueue.main.sync {
}

How to use one button to add scores for different integers (swift3)

Right now i have a purple and red score. I would like to use the 1 and 2 buttons to add the score for the colors. I know how to do this by creating just a sets of buttons to the specific color but doing this again and again will create problems. So what I am trying to do is if purple is selected and if and only if 1 is pressed then the total score of purple will = 1. I guess what I am trying is perform a switch statement for the buttons.
Before purple/red button is pressed.
After purple/red button is pressed.
import UIKit
class ViewController: UIViewController {
var purpleScore = 0
var redScore = 0
#IBOutlet var plus1: UIButton!
#IBOutlet var plus2: UIButton!
#IBOutlet var addRed: UIButton!
#IBOutlet var addPurlple: UIButton!
#IBOutlet var totalScorePurple: UILabel!
#IBOutlet var totalScoreRed: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
plus1.isHidden = true
plus2.isHidden = true
}
#IBAction func enteringRed(_ sender: Any) {
plus1.isHidden = false
plus2.isHidden = false
}
#IBAction func enteringPurple(_ sender: Any) {
plus1.isHidden = false
plus2.isHidden = false
}
#IBAction func plus1(_ sender: Any) {
}
#IBAction func plus2(_ sender: Any) {
}
}
If I understand correctly as the comment above, this should work
Create 2 Bool for red and purple to see weather they are checked or not, this is easiest way, else you can just check the redButton color got changed (if it does) or .selected = true
var redChecked = false
var purpleChecked = false
#IBAction func enteringRed(_ sender: Any) {
redChecked = !redChecked
//change color etc..
}
#IBAction func enteringPurple(_ sender: Any) {
purpleChecked = !purpleChecked
//change color etc..
}
#IBAction func plus1(_ sender: Any) {
if redChecked {
redScore+=1
}
if purpleChecked {
purpleScore+=1
}
}
#IBAction func plus2(_ sender: Any) {
if redChecked {
redScore+=2
}
if purpleChecked {
purpleScore+=2
}
}

How to implement NSUndoManager and arrays in iOS using Swift 2

So quick question. I am writing an iOS app for a dart game. And I am trying to implement an undo button to undo the last action.
Whats going on: When you push any of the buttons they add that amount to the score. The users score that the buttons have an effect on is the currentPlayer.
I want the undo button to undo whatever button was pushed last. I have been researching and it seems like they are all showing how to hard code an undo action. However it could be any of the 6 buttons hit_single, hit_double, attack_double... etc.
FIRST: I don't know how to use undoManager.registerUndoWithTarget(target:AnyObject, selector: Selector, object: AnyObject?), I'm not sure how to apply this and what each of these 3 things do.
SECOND: In my game you have to go from 1-20(the numbers on a dart board) and then hit bullseye to win. The variables user1score and user2score increase their count to display what number the player is aiming at. However, after 20 I want the score to display "Bullseye". I am not sure if there is a way to write a mixed content array, one that allows counting 1-20, and then the 20th array value say "Bullseye". Or maybe write an If statement that says if the user1score/user2score is greater than 20 print "Bullseye". The problem is it says its an integer and I cant input a string value.
Here is my code:
import UIKit
class Galaxy_VC: UIViewController {
#IBOutlet var currentPlayerName: UILabel!
#IBOutlet weak var user1score: UILabel!
#IBOutlet weak var user2score: UILabel!
#IBOutlet weak var darts_Thrown: UILabel!
var names = ["Big Meat", "J Hooks"]
var currentPlayer = 0
var scores = [0, 0]
var count = 0
override func viewDidLoad() {
super.viewDidLoad()
setupGame()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupGame() {
user1score.text = "\(count)"
user2score.text = "\(count)"
}
func updateTurn() {
currentPlayerName.text = names[currentPlayer]
user1score.text = "\(scores[0])"
user2score.text = "\(scores[1])"
}
func undoLast(score: NSNumber) {
undoManager?.registerUndoWithTarget(self, handler: <#T##AnyObject -> ()#>)
}
#IBAction func btn_NextTurn(sender: UIButton) {
currentPlayer = 1 - currentPlayer
updateTurn()
}
#IBAction func btn_UndoTurn(sender: AnyObject) {
}
#IBAction func hit_Single(sender: AnyObject) {
scores[currentPlayer] + 1
updateTurn()
}
#IBAction func hit_Double(sender: AnyObject) {
scores[currentPlayer] + 2
updateTurn()
}
#IBAction func hit_Triple(sender: AnyObject) {
scores[currentPlayer] + 3
updateTurn()
}
#IBAction func Miss(sender: AnyObject) {
scores[currentPlayer] - 1
updateTurn()
}
#IBAction func attack_double(sender: AnyObject) {
scores[1 - currentPlayer] - 2
updateTurn()
}
#IBAction func attack_Triple(sender: AnyObject) {
scores[1 - currentPlayer] - 3
updateTurn()
}
}
Any help you can provide would be really appreciated! Thanks!

How do you get a UI button to do different tasks each time it is pressed?

When I create an IBaction for a button I can easily get it to perform an action for example:
#IBAction func click(sender: AnyObject) {
label6.hidden = false}
How do I get it to execute a totally different task when it is clicked for a second or third time etc?
Thanks
EDIT: When I try this I get an error "Viewcontroller.type does not have a member named "label1", this also is stated for "label2" Any ideas why as I have already added the label in as an outlet. Do I need to declare it somewhere else to get it to work? Thanks
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
label1.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
class MyButtonClass
{
var clickCounter: Int = 0
#IBAction func click(sender: AnyObject)
{
clickCounter += 1
if (clickCounter == 1)
{label1.text = "text1"}
else if (clickCounter == 2)
{label2.text = "text1"
clickCounter = 0}
}
}
}
Replace your code with the following:
class ViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
label1.text = ""
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
var clickCounter: Int = 0
#IBAction func click(sender: AnyObject)
{
clickCounter += 1
if (clickCounter == 1)
{
label1.text = "text1"
}
else if (clickCounter == 2)
{
label2.text = "text1"
clickCounter = 0
}
}
}
You can have a counter and depending on its value fire another method from the one called on click
Create a property that counts the tap count
Increment the tap count on each click
Implement a switch on the tap count to perform different actions (IBAction acts as a dispatcher)

Resources