Более 1 rightBarButtonItem на панели навигации - PullRequest
24 голосов
/ 31 мая 2009

Я хотел бы иметь два элемента rightBarButton на панели навигации. Один для редактирования, а другой для добавления.

Очевидно, я не могу сделать это с помощью Interface Builder.

Кто-нибудь знает, как это сделать программно? Спасибо!

Ответы [ 9 ]

68 голосов
/ 04 февраля 2012

Теперь это включено в iOS 5 и называется rightBarButtonItems, обратите внимание на множественное число

Вот текст из яблочных документов :

rightBarButtonItems

Массив пользовательских элементов панели кнопок для отображения в правой части панели навигации когда получатель является главным элементом навигации.

@ свойство (неатомное, копировать) NSArray * rightBarButtonItems

Обсуждение

Этот массив может содержать 0 или более элементов кнопок панели для отображения справа от
Панель навигации. Элементы отображаются справа налево в том же порядке, в котором они отображаются в массив. Таким образом, первый элемент в массиве является самым правым элементом, и другие элементы добавляются слева от предыдущего элемента.

Если недостаточно места для отображения всех элементов в массиве, те, которые будут перекрывать вид заголовка (если имеется) или кнопки на левой стороне панели не являются
отображается.

Первый элемент в массиве также можно установить с помощью свойства rightBarButtonItem.

объявлено в UINavigationBar.h

Вот как я реализовал значок поиска и значок редактирования в правой части навигационной панели:

UIBarButtonItem *searchButton         = [[UIBarButtonItem alloc]
                                         initWithBarButtonSystemItem:UIBarButtonSystemItemSearch
                                         target:self
                                         action:@selector(searchItem:)];

UIBarButtonItem *editButton          = [[UIBarButtonItem alloc] 
                                         initWithBarButtonSystemItem:UIBarButtonSystemItemEdit
                                         target:self action:@selector(editItem:)];

self.navigationItem.rightBarButtonItems =
[NSArray arrayWithObjects:editButton, searchButton, nil];
37 голосов
/ 01 сентября 2009

Вот пример того, как вы можете добавить две кнопки в качестве правой кнопки. Приведенный ниже код создает сегментированный элемент управления, содержащий кнопки со стрелками вверх и вниз, которые затем добавляются в качестве настраиваемого представления для правой кнопки навигации:

UISegmentedControl* segmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray array]];
    [segmentedControl setMomentary:YES];
    [segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"icon-triangle-up.png"] atIndex:0 animated:NO];
    [segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"icon-triangle-down.png"] atIndex:1 animated:NO];
    segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
    [segmentedControl addTarget:self action:@selector(segmentedAction:) forControlEvents:UIControlEventValueChanged];

    UIBarButtonItem * segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView: segmentedControl];
    self.navigationItem.rightBarButtonItem = segmentBarItem;
4 голосов
/ 01 июня 2009

Мое предложение состоит в том, чтобы не реализовывать функцию «Добавить» в виде кнопки на панели навигации. Я предполагаю, что вы имеете дело с табличным представлением элементов ниже, поэтому одним из способов обработки этого взаимодействия с пользователем является отображение опции «Добавить новый элемент» в качестве последней записи в табличном представлении. Это может быть программно затенено, когда пользователь нажимает кнопку «Изменить» на панели навигации, реализуя следующий метод делегата:

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [self.tableView beginUpdates];
    [self.tableView setEditing:editing animated:YES];

    if (editing)
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[objects count] inSection:0];
        [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];           
    }
    else
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[objects count] inSection:0];     
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];           
    }
    [self.tableView endUpdates];
}

Затем вам необходимо убедиться, что дополнительная строка учтена путем увеличения количества строк с использованием следующего:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    if (tableView.editing)
        return ([objects count] + 1);
    else
        return [objects count];     
}

и затем показывает зеленый знак плюс слева от него, в отличие от обычного стиля редактирования удаления:

- (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    if (self.editing == NO || !indexPath) return UITableViewCellEditingStyleNone;
    if (indexPath.row >= [objects count]) 
        return UITableViewCellEditingStyleInsert;
    else
        return UITableViewCellEditingStyleDelete;

    return UITableViewCellEditingStyleNone;
}

Конечно, вам нужно будет указать имя для него в своей cellForRowAtIndexPath: реализации и также обработать выбор строки.

2 голосов
/ 04 сентября 2011

Вот действительно простой ответ из двух строк:

Шаг 1. Создайте перо для пользовательского представления с любым содержимым, которое вы хотите

Шаг 2. Добавьте перо на панель инструментов в качестве пользовательского представления:

NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"TwoButtonView" owner:self options:nil];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[subviewArray objectAtIndex:0]];
2 голосов
/ 26 августа 2011

Если вы хотите иметь две отдельные кнопки в качестве rightBarButtonItem, вы можете сделать это, добавив UIToolbar в качестве настраиваемого представления к правой панели:

/*************************************************
       CREAT TWO RIGHT BAR BUTTON ITEMS
   *************************************************/
    // create a toolbar to have two buttons in the right
    UIToolbar* customToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 90, 44.01)];

    // create the array to hold the buttons, which then gets added to the toolbar
    NSMutableArray* rightBarButtonArray = [[NSMutableArray alloc] initWithCapacity:2];

    //Add the info button to the array
    UIButton* infoViewButton = [[UIButton buttonWithType:UIButtonTypeInfoLight] retain];
    [infoViewButton addTarget:self action:@selector(showInfoView) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *infoItem =  [[UIBarButtonItem alloc] initWithCustomView:infoViewButton];
    [rightBarButtonArray addObject:infoItem];
    [infoItem release];

    //Add the Done Button to the array
    UIBarButtonItem *bbi;
    bbi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone 
                                                        target:self 
                                                        action:@selector(create:)];

    [rightBarButtonArray addObject:bbi];
    [bbi release];

    //add the array to the custom toolbar
    [customToolbar setItems:rightBarButtonArray animated:NO];
    [rightBarButtonArray release];

    // and finally add the custom toolbar as custom view to the right bar item
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customToolbar];
    [customToolbar release];
2 голосов
/ 31 мая 2009

панель навигации - это UIView, так что вы можете просто создать регулярную кнопку UIB и добавить ее на панель навигации в качестве subView.

Установить кадр относительно навигационной панели. Если вы хотите, чтобы она выглядела точно так же, как встроенная кнопка, вам, вероятно, придется создавать графику самостоятельно, поскольку она не отображается в SDK AFAIK.

0 голосов
/ 18 июля 2016

если кто-то проходит мимо, вот быстрый ответ:

let barButton_array: [UIBarButtonItem] = [Button1, Button2]
navigationItem.setRightBarButtonItems(barButton_array, animated: false)
0 голосов
/ 28 января 2015

Вы можете сделать это из Интерфейсного Разработчика. Что я сделал в своем приложении - просто добавил UIView в левой части панели навигации и поместил 3 кнопки в этом представлении и связал их действие Вы можете добавить несколько кнопок в левый / правый элемент навигации.

Ссылка: Элементы панели инструментов в суб-перо

enter image description here

0 голосов
/ 27 февраля 2012

Для отображения независимых кнопок (вместо сегментированных кнопок управления):

// create a toolbar to have two buttons in the right
UIToolbar* tools = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 133, 44.01)];

// create the array to hold the buttons, which then gets added to the toolbar
NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:3];

// create a standard "add" button
UIBarButtonItem* bi = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:NULL];
bi.style = UIBarButtonItemStyleBordered;
[buttons addObject:bi];

// create a spacer
bi = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
[buttons addObject:bi];

// create a standard "refresh" button
bi = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh:)];
bi.style = UIBarButtonItemStyleBordered;
[buttons addObject:bi];

// stick the buttons in the toolbar
[tools setItems:buttons animated:NO];

// and put the toolbar in the nav bar
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:tools];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...