View Tint In iOS 7

An important part of developing with iOS 7 is having a consistent look and feel for our apps. One way this is achieved is through the use of tint. A view’s tint property defines the tint color applied to all of its controls. In this blog, we’ll look at applying a tint color to a view and overriding that tint color when we want to draw particular attention to a single control in the view. The source code for this project is available hereTintDemo

As always, start Xcode and create a new project. In this case, create a single view application. After saving the app, open Interface Builder by selecting the Main.Storyboard file. Select the view, and change its tint color to green:

 

Now drag a button control to the view. Notice that it is tinted green because it inherits its tint from its parent view. Change the text on the button to “On” as shown here:

 

We’ll now create the action method for this button. Open ViewController.h and add the method prototype:

#import <UIKit/UIKit>

@interface ViewController : UIViewController

- (IBAction)btnPressed:(UIButton *)sender;

@end

Now we’ll add the implementation of this method to the ViewController.m file:

- (IBAction)btnPressed:(UIButton *)sender
{
    if ([sender.titleLabel.text isEqualToString:@"On"]) {
        [sender setTitle:@"Off" forState:UIControlStateNormal];
        [sender setTintColor:[UIColor redColor]];
    } else {
        [sender setTitle:@"On" forState:UIControlStateNormal];
        [sender setTintColor:self.view.tintColor];
    }
}

In the above code, we toggle between two states of the button by not only changing the text, but also overriding the view’s tint color. Notice that when we set the title back to “On,” we use the parent’s tint color (self.view.tintColor) to reset the button’s tint.

Wire this method up to the button’s TouchUpInside event in interface builder, then run the app.

 

Experiment with different tint colors on different controls. For example, you might want to try changing the tint of a slider control as it is moved from left to right, or that of a segmented control depending on which segment is currently selected. Keep in mind that you could also change the tint for the entire view, thus altering the tint of all controls belonging to it.

Keep coding, and Have Fun!

Leave a Comment: