I prepared a label and a button on the storyboard, and when I ran the code below, the label now says "A" when I press the button.
How can I change the characters displayed according to the number of taps, such as "i" on the second tap and "u" on the third tap?
import UIKit
classViewController:UIViewController {
@IBOutlet weak var Label: UILabel!
@ IBAction func Button(_sender:UIButton){
Label.text="Ah"
}
}
The processing changes depending on the number of times you tap, so you must first save the number of times you tap to the variable.
Then change the value to replace the label according to the number of times you tap using that variable.
class ViewController:UIViewController {
@IBOutlet weak var Label: UILabel!
vartapCount = 0
@ IBAction func Button(_sender:UIButton){
tapCount+=1
iftapCount==1 {
Label.text="Ah"
} else if tapCount == 2 {
Label.text="Yes"
} else if tapCount == 3 {
Label.text="U"
}
...
}
}
In the previous answer,
There is a mistake inTo reduce these errors, the following are examples of avoiding coding directly:
class ViewController:UIViewController {
@IBOutlet weak var Label: UILabel!
let labels = ["a", "i", "u", "e", "o", "ka", "ki", "ku", "ke", "ko" ]
vartapCount = 0
@ IBAction func Button(_sender:UIButton){
Label.text=labels [tapCount%labels.count]
tapCount+=1
}// end func Button
}// end class ViewController
By placing the label string in the array and determining the index of which character (string) to use in the array from the counter and the number of arrays, even if the array length is changed, the number of taps will be picked up again from the beginning.
It also has the advantage of being easy to see and modify because the strings you want to display on the label are all in one place.
© 2024 OneMinuteCode. All rights reserved.