Xcode - Label won't clear when button is pressed - ios

So I'm trying to create a simple function in my app in which a button adds 1 integer to the label when it's pressed and the other one clears it.
Here is the code:
class ViewController: UIViewController {
var number = 0
#IBOutlet weak var tapCount: UILabel!
#IBAction func plusTapped(sender: AnyObject) {
number = number + 1
tapCount.text = String(number)
}
#IBAction func minusTapped(sender: AnyObject) {
var totalNumber = number - number
tapCount.text = String(totalNumber)
}
However the label does clear when the minus button is tapped but when the plus button is tapped after, it adds up from the previous number before the minus button was pressed.
How do I fix this in a way so that it actually clears the label?

#IBAction func minusTapped(sender: AnyObject) {
number = 0 // add this line to reset the counter, the real number
tapCount.text = String(number)
}

Try
#IBAction func minusTapped(sender: AnyObject) {
number = 0
tapCount.text = String(0)
}

I think it's because when you're handling tap on minus you are altering local variable and not changing number itself. You should change "number" too. Se my comments in your's code
class ViewController: UIViewController {
var number = 0
#IBOutlet weak var tapCount: UILabel!
#IBAction func plusTapped(sender: AnyObject) {
number = number + 1
tapCount.text = String(number)
}
#IBAction func minusTapped(sender: AnyObject) {
//here totalNumber is changed but number is still the same
var totalNumber = number - number
tapCount.text = String(totalNumber)
}

Related

How to go through array with button press

I have an array that contains different information,
how can I iterate through the array with a button press? I have two buttons, and I need to allow one to move forward in the array and the back button to display the previous index.
#IBOutlet weak var backButton: UIButton!
#IBOutlet weak var nextButton: UIButton!
#IBOutlet weak var infoLabel: UILabel!
#IBOutlet weak var pageControl: UIPageControl!
Let infoArray = ["info1","info2","info3","info4"]
#IBAction func nextTapped(_ sender: Any) {
// Change the label based on the selected index in array
}
#IBAction func backTapped(_ sender: Any) {
//Return to previous index and update label text
}
I also added page control for better UX, but for now I'm just worried about learning how to even change the label through button Tap.
My guess would be to start the index at 0 which would be info1 and go from there. I can worry about saving index state later.
Any help is much appreciated.
The logic should look something like this
let infoArray = ["info1","info2","info3","info4"]
func viewDidLoad() {
pageControl.numberOfPages = infoArray.count
pageControl.currentPage = 0
}
#IBAction func nextTapped(_ sender: Any) {
// Change the label based on the selected index in array
guard pageControl.currentPage + 1 < infoArray.count else {
return
}
pageControl.currentPage += 1
}
#IBAction func backTapped(_ sender: Any) {
//Return to previous index and update label text
guard pageControl.currentPage - 1 >= 0 else {
return
}
pageControl.currentPage -= 1
}
When a user taps a page control to move to the next or previous page, the control sends the valueChanged event for handling by the delegate. The delegate can then evaluate the currentPage property to determine the page to display. The page control advances only one page in either direction.
Please check the below code you can do something like this to move your array forward and backward. Please add other checks according to your need.
var i = 0
let infoArray = ["info1","info2","info3","info4"]
#IBAction func nextTapped(_ sender: Any) {
// Change the label based on the selected index in array
if i >= 0 && i < infoArray.count{
dataLbl.text = infoArray[i]
}
if i > 3 {
i = i-1
} else {
i = i+1
}
}
#IBAction func backTapped(_ sender: Any) {
//Return to previous index and update label text
if i >= 0 && i < infoArray.count-1 {
dataLbl.text = infoArray[i]
}
if i < 0 {
i = i+1
} else {
i = i-1
}
}

Hiding UIButton if variable has certain value?

I want to hide a UIButton as long as a certain variable has not reached a certain value.
I tried some setHidden and isHidden setups, but I guess I did it all wrong. I don't exactly know where to put these commands.
I have looked for a solution at almost every webpage but I got no idea what everybody is talking about.
import UIKit
class ViewController: UIViewController {
let startvalue = 1000000
#IBOutlet weak var Counter: UITextField!
#IBAction func Button(_ sender: UIButton) {
if number > 1{
number -= 1
Counter.text = String(number)
} else {
Counter.text = "Hurray"
}
}
#IBOutlet weak var Reset: UIButton!
#IBAction func Reset(_ sender: UIButton) {
if number == 1{
number = startvalue
Counter.text = String (number)
}
}
override func viewDidLoad() {
var number = startvalue {
didSet {
if number < 1 {
Reset.isHidden = false
}
}
}
super.viewDidLoad()
}
}
I don't now what I need to put where to hide Result as long as number is greater than 1.
Handle it in the didSet of the variable.
var number = startValue {
didSet {
if number < 1 {
yourButton.isHidden = false
}
}
}
Now, whenever your number is changed, the didSet block will check if the value is less than 1. If so, it'll unhide the button.
Note: Make sure the button is hidden before the view shows. Also, make sure to hide the button if needed on resetting.
Use lowerCamelCase for variable names like they say in the API design guidelines.

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)"
}
}

How can I change the title of a group of buttons with an array?

I have two IBAction groups with three buttons each.
Each button has a different tag - within each group: 1, 2 and 3.
I have three arrays, with three values each.
I want to press the first button of the first IBAction and change the title of the three buttons in the second IBAction, based on the group of arrays.
Here is the code:
import UIKit
class ViewController: UIViewController {
var firstArray = ["A1","A2","A3"]
var secondArray = ["B1","B2","B3"]
var thirdArray = ["C1","C2","C3"]
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func greenButtons(_ sender: UIButton) {
if sender.tag == 1 {
//change the title of the grayButtons with the firstArray
}
if sender.tag == 2 {
//change the title of the grayButtons with the secondArray
}
if sender.tag == 3 {
//change the title of the grayButtons with the thirdArray
}
}
#IBAction func grayButtons(_ sender: UIButton) {
}
}
You can try
// create outlet group for each
#IBOutlet weak var greenButtons:[UIButton]!
#IBOutlet weak var grayButtons:[UIButton]!
Inside action of greenButtons
grayButtons.forEach { $0.setTitle(firstArray[$0.tag - 1],for:.normal) }
Instead of if check you can construct the array as
let allArr = [ ["A1","A2","A3"], ["B1","B2","B3"],["C1","C2","C3"]]
Then
grayButtons.forEach { $0.setTitle(allArr[sender.tag - 1][$0.tag - 1],for:.normal) }

Swift - the text field returns 0 even though I inserted a different number

I'm new to Swift, and I'm trying to make a little app that, given two values (a,b) returns a random number between the two numbers (a < randomnumber < b)
The user has to write the values of a and b in two different text fields and then just press a button and that's it
The problem is:
I told the NSLog to display the two values just before generating the random number because I noticed something wasn't working as it was supposed to, and the result is that apparently the second value I insert, whether it is a or b, for some (unknown) reason, equals 0 ! For example, if I write in the a-textfield the value 10 and then I insert the value 40 in the b-textfield, the NSLog displays a = 10, b = 0. If I insert the b value before, the NSLog displays b = 40, a = 0.
These are the lines of code :
#IBAction func TextAAction(sender: AnyObject) {
a = UInt32(TextA.text!)!
}
#IBAction func TextBAction(sender: AnyObject) {
b = UInt32(TextB.text!)!
}
#IBAction func randomInBetweenAction(sender: AnyObject) {
NSLog("a=%ld, b=%ld", a, b)
randomInBetween()
unHide()
Label.text = "\(randomNumberInBetween)"
}
as you can see the value a is equal to the value that is inserted in the TextA field and the value b is equal to the value that is inserted in the TextB field
the randomInBetween() is the function that generates a random number between a and b, and it does work.. the problem is that one of the values (the second one I insert) is always 0 for some reason, even if I set it to a different number!
Any ideas on why this happens and how to work it out?
#ReinerMelian this is the full code
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var Label: UILabel!
#IBOutlet weak var Button: UIButton!
#IBOutlet weak var InvariableLabel: UILabel!
#IBOutlet weak var TextA: UITextField!
#IBOutlet weak var TextB: UITextField!
#IBOutlet weak var AndLabel: UILabel!
#IBOutlet weak var Button2: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Hide()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var randomNumber = Int()
func randomNUMBER() -> Int {
randomNumber = Int(arc4random())
return randomNumber
}
func Hide() {
Label.hidden = true
}
func unHide() {
Label.hidden = false
}
var a = UInt32()
var b = UInt32()
var randomNumberInBetween = Int()
func randomInBetween() -> Int {
if b>a {
randomNumberInBetween = Int(arc4random_uniform(b - a) + a)
return randomNumberInBetween
} else {
randomNumberInBetween = Int(arc4random_uniform(a - b) + a)
return randomNumberInBetween
}
}
#IBAction func ButtonAction(sender: AnyObject) {
randomNUMBER()
unHide()
Label.text = "\(randomNumber)"
NSLog("\(randomNumber)")
}
#IBAction func TextAAction(sender: AnyObject) {
a = UInt32(TextA.text!)!
}
#IBAction func TextBAction(sender: AnyObject) {
b = UInt32(TextB.text!)!
}
#IBAction func randomInBetweenAction(sender: AnyObject) {
NSLog("a=%ld, b=%ld", a, b)
randomInBetween()
NSLog("\(randomInBetween)")
unHide()
Label.text = "\(randomNumberInBetween)"
NSLog("\(randomInBetween)")
}
}
(PS: as you can see, there is also a function that generates a random number without any sort of constraints, but that part works just fine.. the problem is with the other part of the code, the one that returns a random number between two given values (a,b) )
make sure, your outlets (TextA, TextB) and your IBAction (randomInBetweenAction) are wired up correctly, remove
#IBAction func TextAAction(sender: AnyObject) {
a = UInt32(TextA.text!)!
}
and
#IBAction func TextBAction(sender: AnyObject) {
b = UInt32(TextB.text!)!
}
and try this function on button tap:
#IBAction func randomInBetweenAction(sender: AnyObject) {
a = UInt32(TextA.text!)!
b = UInt32(TextB.text!)!
NSLog("a=%ld, b=%ld", a, b)
randomInBetween()
NSLog("\(randomInBetween)")
unHide()
Label.text = "\(randomNumberInBetween)"
NSLog("\(randomInBetween)")
}

Resources