Reputation: 4810
This is hopefully really simple.
I'm building a basic calculator application to learn iOS and Swift, and I'm attempting to implement code for the clear button.
As the standard goes, the clear button (implemented with a basic UIButton) displays a "AC" when the display is already cleared (only contains a 0), and displays a "C" otherwise.
My first idea for implementing this is with an IBAction that executes whenever the UILabel display's text changes. Apparently, this is not an action already implemented for UILabel. Is there another way to create this IBAction, or should I take another approach?
Upvotes: 0
Views: 96
Reputation: 4810
Found a really slick solution for my problem after some more tinkering!
@IBOutlet weak var clearButton: UIButton!
@IBOutlet weak var display: UILabel! {
didSet {
if display.text == "0" {
clearButton.setTitle("AC", forState: UIControlState.Normal)
}
else {
clearButton.setTitle("C", forState: UIControlState.Normal)
}
}
}
The only catch is that when the clear button is pressed when the title is "C", it does not automatically change to "AC". This is fixed with the following IBAction for the clear button:
@IBAction func clearTouchUpInside() {
if clearButton.currentTitle == "AC" {
calculator.clear()
}
display.text = "0"
clearButton.setTitle("AC", forState: UIControlState.Normal)
}
Upvotes: 0
Reputation: 3126
IBAction
is basically the simplified way of associating a method to events of controls you drop on your storyboard or xib. It's just one way (out of 2 or 3) of wiring your view to your controller.
You should make all the buttons on your calculator call the same method and pass the pressed button as an argument, something like (void)buttonPressed:(id)button
then check the pressed button to change the display value and set the (A)C button accordingly.
Upvotes: 1
Reputation:
Use KVO (key value Observing).
Generate notification whenever any key (UILabel's text property) referencing value changes.
Have a wide idea about it here
Upvotes: 3