1

I have one button -(IBAction)mode;, and I would like it to change my label text each time it is pressed, so as to switch modes like modes on a digital watch. Then I would like to use these modes in if-then statements to make different calculations.

As for the if-then statements, I can just say something like,

if label = x then, if label = y then

But how do you create the button that changes the text of the same label each time it is pushed? Any help is appreciated.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
George Friday
  • 585
  • 1
  • 6
  • 22

1 Answers1

1

Then I would like to use these modes in if-then statements to make different calculations.

Although you can certainly do that, I would strongly advice you against going this route: using the content of a label in calculations runs against the grain of the Model View Controller pattern, because label content is part of a visual representation, while calculations are part of the logical model.

This is more than just a theoretical problem - far from it: using label content prevents localization, and impedes future maintenance of your project.

Here is how to achieve what you are looking for in an MVS way:

  • Define a model class that stores the current mode switchable on the button
  • Define methods in the model or in the controller that perform calculations based on the current mode
  • Define methods to get the current mode and to toggle the mode as necessary
  • Make sure the model object is a singleton in your project
  • In the view for the "view will appear" method read the mode from the model, and set the label accordingly
  • In the code for the button handler, read the current mode, change it as necessary, store back the new value, and update the label accordingly.

This sounds like a lot of work, but the Objective C code for this approach is not much lengthier than the approach that reads from labels directly.

Here is a short example of setting up a model as a singleton in Objective C.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thank you for your reply. This sounds brilliant... and complicated... looks like I am going to hit the books to find out how to do this. I am not that advanced when it comes to Xcode (yet). – George Friday Jul 14 '13 at 18:09