Я хотел бы иметь два rightBarButtonItems на панели навигации. Один для редактирования, а другой для добавления.
Очевидно, я не могу сделать это с помощью Interface Builder.
Кто-нибудь знает, как это сделать программно? Спасибо!
Я хотел бы иметь два rightBarButtonItems на панели навигации. Один для редактирования, а другой для добавления.
Очевидно, я не могу сделать это с помощью Interface Builder.
Кто-нибудь знает, как это сделать программно? Спасибо!
Теперь это включено в iOS 5 и называется rightBarButtonItems, обратите внимание на множественное число
Вот текст из яблочных документов:
rightBarButtonItems
Массив элементов пользовательских элементов панели, отображаемых с правой стороны панели навигации когда приемник является верхним элементом навигации.
@property (неатомный, копия) 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];
Вот пример того, как вы можете добавить две кнопки в качестве правой панели. В приведенном ниже коде создается сегментированный элемент управления, содержащий кнопки со стрелками вверх и вниз, которые затем добавляются в качестве настраиваемого режима для правой панели навигации:
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;
Мое предложение состояло в том, чтобы не реализовать функцию добавления в качестве кнопки на панели навигации. Я предполагаю, что вы имеете дело с табличным представлением элементов ниже, поэтому одним из способов обработки этого взаимодействия с пользователем является отображение опции "Добавить новый элемент" в качестве последней записи в виде таблицы. Это может быть программно исчезло, когда пользователь нажал кнопку "Редактировать" на панели навигации, выполнив следующий метод делегирования:
- (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: реализация и обработать его выбор строки.
панель навигации представляет собой UIView, поэтому вы можете просто создать regulat UIButton и добавить его в свою панель навигации в качестве подвид.
Установите рамку относительно панели навигации. Если вы хотите, чтобы он выглядел точно так же, как встроенная кнопка, вам, вероятно, придется самому создавать графику, поскольку они не подвергаются воздействию SDK AFAIK.
Если вы хотите иметь две выделенные кнопки в качестве 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-строчный ответ:
Шаг 1: Создайте наконечник для пользовательского представления с любым содержимым, которое вы хотите
Шаг 2. Добавьте плитку на панель инструментов в виде пользовательского вида:
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"TwoButtonView" owner:self options:nil];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[subviewArray objectAtIndex:0]];
Чтобы показать независимые кнопки (вместо сегментированных кнопок управления):
// 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];
Вы можете сделать это из интерфейса Builder. То, что я сделал в своем приложении, просто добавил UIView в левой части панели навигации и разместил 3 кнопки в этом представлении и связал их действие. Вы можете следить за этим, чтобы добавить несколько кнопок в элемент навигации слева/справа.
Refered: Элементы панели инструментов в суб-nib
если кто-то проходит мимо, вот быстрый ответ:
let barButton_array: [UIBarButtonItem] = [Button1, Button2]
navigationItem.setRightBarButtonItems(barButton_array, animated: false)