2010-09-14 2 views
2

Дорогой все, что я реализовал две кнопки в панели навигации справа от текстового вида;Как скрыть одну из двух правых кнопок на панели навигации

UIToolbar* toolbar = [[UIToolbar alloc] 
         initWithFrame:CGRectMake(0, 0, 112, 44.5)]; 

// toolbar style is the default style 

// create an array for the buttons 

NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:3]; 

// create a button to run the job 
UIBarButtonItem *runButton = [[UIBarButtonItem alloc] 
           initWithTitle:@"RUN" 
           style:UIBarButtonItemStyleBordered 
           target:self 
           action:@selector(runAs:)]; 
// Button style is the default style 
[buttons addObject:runButton]; 
[runButton release]; 

// create a spacer between the buttons 

UIBarButtonItem *spacer = [[UIBarButtonItem alloc] 
          initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace 
          target:nil 
          action:nil]; 
[buttons addObject:spacer]; 
[spacer release]; 

// create a standard Edit/Done button with custom titles Edit/Save 

self.editButtonItem.possibleTitles = [NSSet setWithObjects:@"Edit", @"Save", nil]; 
self.editButtonItem.title = @"Edit"; 
UIBarButtonItem *editButton = self.editButtonItem; 
[buttons addObject:editButton]; 
[editButton release]; 

// put the buttons in the toolbar and release them 
[toolbar setItems:buttons animated:YES]; 
[buttons release]; 

// place the toolbar into the navigation bar as Right Button item 
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] 
              initWithCustomView:toolbar]; 
[toolbar release]; 

Теперь в режиме редактирования Я хочу, чтобы скрыть кнопку RUN и когда кнопка RUN находится в действии, я хочу кнопку Изменить, чтобы скрыть. Может ли кто-нибудь предложить мне способ сделать это без переопределения кнопок в режиме редактирования (например, для элемента back/left button setHidesBackButton: (BOOL) animated: (BOOL)) или любого альтернативного метода? Большое спасибо.

ответ

2

Попробуйте это:

UIToolbar *toolbar = (UIToolbar *) self.navigationItem.rightBarButtonItem.customView; 
UIBarButtonItem *runButton = (UIBarButtonItem *) [toolbar.items objectAtIndex: 0]; 
runButton.customView.hidden = YES; 
+0

Уважаемый Джейкоб, Спасибо за ответ. Я пробовал приведенный выше код, но он дает ошибку «скрытый - это что-то не структура или объединение», возможно, потому что «runButton» не является UIButton, это UIBarButtonItem. [runButton setHidden: (BOOL)] не работает, но [runButton setEnabled: (BOOL)] работает. Любое дальнейшее предложение будет высоко оценено. Спасибо – UCU110

+0

@ UCU110, попробуйте мой обновленный ответ. –

0

мне нужно, чтобы показать/скрыть один из двух кнопок исключительно. Я создал категорию в NSMutableArray, удалил обе кнопки, если они находятся в массиве, а затем добавил каждый, если это необходимо. Вероятно, вам нужно будет иметь кнопки в качестве свойств на вашем ViewController.

NSMutableArray + Расширения

@implementation NSMutableArray (Extensions) 
-(bool)removeItemIfExists:(id)item { 
    bool wasRemoved=false; 
    for (int i=self.count-1;i>0;i--) { 
     if([self objectAtIndex:i] == item){ 
      [self removeObjectAtIndex:i]; 
      wasRemoved = true; 
     } 
    } 
    return wasRemoved; 
} 
@end 

Вызов его с помощью:

NSMutableArray *newLeftItems = [self.navigationItem.leftBarButtonItems mutableCopy]; 
[newLeftItems removeItemIfExists:btnOne]; 
[newLeftItems removeItemIfExists:btnTwo]; 
if(someCondition) { 
    [newLeftItems insertObject:btnOne atIndex:1]; 
} else { 
    [newLeftItems insertObject:btnTwo atIndex:1]; 
} 
[self.navigationItem setLeftBarButtonItems:newLeftItems animated:true]; 
0

Попробуйте это ..

-(void) changeBarButtonVisibility:(UIBarButtonItem*) barButtonItem visibility:(BOOL) shouldShow { 
UIColor *tintColor = shouldShow == NO ? [UIColor clearColor] : nil; 
[barButtonItem setEnabled:shouldShow]; 
[barButtonItem setTintColor:tintColor]; 

}

и позвоните по вышеуказанному методу и пропустите кнопку панели, которую вы хотите скрыть.

[self changeBarButtonVisibility:self.navigationItem.rightBarButtonItems[0] visibility:NO]; 
[self changeBarButtonVisibility:self.navigationItem.rightBarButtonItems[1] visibility:YES];