![](/img/trans.png)
[英]How to set an action for barbutton item programatically objective-c
[英]Wrong barButton item tint for play/pause buttons built programatically
我有一個帶有音頻控件的UIToolbar。 在iOS 7升級前后的某個時間,欄的顏色發生了變化,iOS開始以不同的方式為我的按鈕添加陰影。 這就引入了一個錯誤,其中我以編程方式更改的播放和暫停按鈕與工具欄的新外觀不匹配:
工具欄開始看起來不錯:
現在我按下播放,所以代碼插入了暫停按鈕,但是顏色錯誤:
現在,我按下了暫停鍵,並插入了插入播放按鈕的代碼,再次使用了錯誤的顏色:
我希望播放和暫停按鈕具有與其他按鈕相同的深色外觀。 我認為在構建替換按鈕時,我必須做一些不同的事情。 原始圖標的圖像都是較淺的顏色,但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];
}
}
感謝您的幫助。
檢查以下內容:
如果圖像存儲在圖像資源中,請確保它們是模板圖像 。
然后,您可以A)在Interface Builder中將其色調設置為您喜歡的灰色,或B)像這樣在makeBarButton方法中以編程方式進行設置;
button.tintColor = [UIColor grayColor];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.