Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Color of MPVolumeView Route Button iOS 7

I am designing a Music app for iOS 7 and I want to put the "AirPlay" route selector button directly in my app. I am able to get the button placed just fine, however it doesn't show up because the icon is white and my background is white.

Is there a way to change the color of the Route Button?

Here is the code I'm using to create the button.

self.airPlayButton = [[MPVolumeView alloc] initWithFrame:CGRectZero];
    self.airPlayButton.showsVolumeSlider = NO;
    [self.airPlayButton sizeToFit];
    self.airPlayButton.backgroundColor = [UIColor myGreenColor];
    [self addSubview:self.airPlayButton];

Basically the picture below is what I want, except I want the icon green instead of just it's background.

MPVolumeView Route Button with background changed

like image 359
jrwagz Avatar asked Sep 29 '13 07:09

jrwagz


2 Answers

in reviewing Adams answer I like more clarity in that task. So I safe-guarded that code a bit:

Objective-C:

for( UIView *wnd in volumeView.subviews ) {
    if( [wnd isKindOfClass:[UIButton class] ]) {
        UIButton *button = (UIButton*) wnd;
        UIImage *img = button.currentImage;
        UIImage *img2 = [img imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        [volumeView setRouteButtonImage: img2 forState:UIControlStateNormal];
        break;
    }
}

Swift:

    for view in volumeView.subviews {
        if view.isKindOfClass(UIButton) {
            let buttonOnVolumeView : UIButton = view as! UIButton
            volumeView.setRouteButtonImage(buttonOnVolumeView.currentImage?.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal)
            break;
        }
    }

Now it reacts on the tintColor property of volumeView and if Apple decides to add another button or change the sequence this code will still work.

like image 115
Karsten Avatar answered Sep 19 '22 09:09

Karsten


To expand on lanbo's answer, you can also get the original image of the Route Button and create a copy that uses the UIImageRenderingMode.AlwaysTemplate rendering mode. That way it heeds the current tintColor.

In Swift:

    let volumeView = MPVolumeView()

    if let routeButton = volumeView.subviews.last as? UIButton,
        let routeButtonTemplateImage  = routeButton.currentImage?.imageWithRenderingMode(.AlwaysTemplate)
    {
        volumeView.setRouteButtonImage(routeButtonTemplateImage, forState: .Normal)
    }
like image 43
Adam Bolcsfoldi Avatar answered Sep 18 '22 09:09

Adam Bolcsfoldi