Как скрыть одну из двух правых кнопок на панели навигации - PullRequest
2 голосов
/ 15 сентября 2010

Уважаемые все, я реализовал две кнопки в панели навигации с правой стороны в верхней части текстового представления как;

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 и когда она запущенаКнопка в действии. Я хочу, чтобы кнопка «Редактировать» была скрыта.Может кто-нибудь предложить мне способ сделать это без переопределения кнопок в режиме редактирования (например, есть для элемента кнопки назад / влево setHidesBackButton: (BOOL) animated: (BOOL)) или каким-либо альтернативным методом?Большое спасибо.

Ответы [ 3 ]

2 голосов
/ 15 сентября 2010

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

UIToolbar *toolbar = (UIToolbar *) self.navigationItem.rightBarButtonItem.customView;
UIBarButtonItem *runButton = (UIBarButtonItem *) [toolbar.items objectAtIndex: 0];
runButton.customView.hidden = YES;
0 голосов
/ 01 декабря 2015

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

-(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];
0 голосов
/ 18 марта 2012

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

NSMutableArray + Extensions

@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];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...