以编程方式构建的播放/暂停按钮错误的barButton项目色调

时间:2016-01-24 22:32:10

标签: ios objective-c

我有一个带音频控件的UIToolbar。在iOS 7的某个时候,升级后的条形颜色会发生变化,iOS开始以不同方式对我的按钮进行着色。这引入了一个错误,我以编程方式更改的播放和暂停按钮与工具栏的新外观不匹配:

工具栏开始看起来很好:

Toolbar starts out looking fine

现在我按了播放,所以代码插入暂停按钮但颜色错误:

Now I pressed play so code inserted pause button but wrong color

现在我按下暂停和代码插入播放按钮,再次出现错误的颜色:

Now I pressed pause and code inserted play button, again with wrong color

我希望播放和暂停按钮具有与其他按钮相同的黑暗外观。我假设在构建替换按钮时我必须做一些不同的事情。原始图标图像都是较浅的颜色,但iOS工具栏似乎会从故事板中自动重新着色为较暗的颜色,如第一个屏幕截图所示。

这是我用来构建按钮的代码:

- (UIBarButtonItem *) makeBarButton: (NSString *) imageName action:(SEL)targetAction
{
    UIImage* image = [UIImage imageNamed:imageName];
    CGRect frame = CGRectMake(0 - 20, 0 - 20, image.size.width + 20, image.size.height + 20);
    UIButton *button = [[UIButton alloc] initWithFrame:frame];
    [button addTarget:self action:targetAction forControlEvents:UIControlEventTouchUpInside];
    [button setImage:image forState:UIControlStateNormal];
    [button setShowsTouchWhenHighlighted:YES];
    return [[UIBarButtonItem alloc] initWithCustomView:button];
}

- (void) setAsPlaying:(BOOL)isPlaying
{
    self.rootViewController.playing = isPlaying;

    // we need to change which of play/pause buttons are showing, if the one to
    // reverse current action isn't showing
    if ((isPlaying && !self.pauseButton) || (!isPlaying && !self.playButton))
    {
        UIBarButtonItem *buttonToRemove = nil;
        UIBarButtonItem *buttonToAdd = nil;
        if (isPlaying)
        {
            buttonToRemove = self.playButton;
            self.playButton = nil;
            self.pauseButton = [self makeBarButton:@"icon_pause.png" action:@selector(pauseAudio:)];
            buttonToAdd = self.pauseButton;
        }
        else
        {
            buttonToRemove = self.pauseButton;
            self.pauseButton = nil;
            self.playButton = [self makeBarButton:@"icon_play.png" action:@selector(playAudio:)];
            buttonToAdd = self.playButton;
        }

        // Get the reference to the current toolbar buttons
        NSMutableArray *toolbarButtons = [[self.toolbar items] mutableCopy];

        // Remove a button from the toolbar and add the other one
        if (buttonToRemove)
            [toolbarButtons removeObject:buttonToRemove];
        if (![toolbarButtons containsObject:buttonToAdd])
            [toolbarButtons insertObject:buttonToAdd atIndex:4];

        [self.toolbar setItems:toolbarButtons];
    }
}

感谢您对此的帮助。

1 个答案:

答案 0 :(得分:0)

检查以下内容:

如果图像存储在图片资源中,请确保它们为template images

然后你可以A)在Interface Builder中将它们的色调颜色设置为你喜欢的灰色或B)在makeBarButton方法中以编程方式进行;

button.tintColor = [UIColor grayColor];