Adding Extra State to Buttons

Recipe 2-1 creates a two-state button, providing visuals for on and off states. At times, you may want to implement buttons with further easy-to-distinguish states. Games provide the most common example of this. Many developers implement buttons that typically showcase four states: locked levels, unlocked-but-not-played, unlocked-and-partially-played, and unlocked-and-mastered.

Recipe 2-1 uses a simple Boolean toggle (the isOn instance variable) to store the on/off state and to select the art used (in the toggleButton: method) based on that state. You can easily expand this example for a wider range of art and button states by storing the state as an integer and providing a switch statement for art selection.

Get The Core iOS Developer’s Cookbook, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.