Каков самый простой способ добавить UIToolBar в UITableViewController? Я в зависимости от функциональности редактирования, поэтому я не могу легко сменить UITableViewController на UIViewController.Добавить панель инструментов в UITableViewController
ответ
Нет проблем, UITableViewController
является подклассом UIViewController
. И так получилось, что в iPhone OS 3.0 любой UIViewController
(и подклассы) может работать совместно с UINavigationController
, чтобы предоставить контекстно-зависимую панель инструментов.
Для того, чтобы это работало, вы должны:
- Убедитесь, что вы используете
UINavigationController
, чтобы содержать все контроллеры представлений, которые нужны панель инструментов. - Установить свойство
toolbarsItems
элемента управления, которому требуется панель инструментов.
Это почти так же просто, как установка заголовка контроллера вида, и его следует выполнять таким же образом. Скорее всего, переопределив инициализатор initWithNibName:bundle:
. В качестве примера:
-(id)initWithNibName:(NSString*)name bundle:(NSBundle*)bundle;
{
self = [super initWithNibName:name bundle:bundle];
if (self) {
self.title = @"My Title";
NSArray* toolbarItems = [NSArray arrayWithObjects:
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(addStuff:)],
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch
target:self
action:@selector(searchStuff:)],
nil];
[toolbarItems makeObjectsPerformSelector:@selector(release)];
self.toolbarItems = toolbarItems;
self.navigationController.toolbarHidden = NO;
}
return self;
}
Вы также можете использовать setToolbarItems:animated:
вместо назначения к toolbarItems
собственности, добавлять и удалять элементы в панели инструментов анимационного моды на лету.
Для того, чтобы сделать рецепт PeyloW, чтобы работать, мне нужно добавить следующую строку кода:
self.navigationController.toolbarHidden = NO;
Надежда, которая помогает ...
Согласовано. Мне пришлось поместить этот вызов в метод viewDidLoad, а не переопределение initWithNibName. Тогда он отлично работает. –
Вы только что спасли мой день, спасибо –
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
//Initialize the toolbar
toolbar = [[UIToolbar alloc] init];
toolbar.barStyle = UIBarStyleDefault;
//Set the toolbar to fit the width of the app.
[toolbar sizeToFit];
//Caclulate the height of the toolbar
CGFloat toolbarHeight = [toolbar frame].size.height;
//Get the bounds of the parent view
CGRect rootViewBounds = self.parentViewController.view.bounds;
//Get the height of the parent view.
CGFloat rootViewHeight = CGRectGetHeight(rootViewBounds);
//Get the width of the parent view,
CGFloat rootViewWidth = CGRectGetWidth(rootViewBounds);
//Create a rectangle for the toolbar
CGRect rectArea = CGRectMake(0, rootViewHeight - toolbarHeight, rootViewWidth, toolbarHeight);
//Reposition and resize the receiver
[toolbar setFrame:rectArea];
//Create a button
UIBarButtonItem *infoButton = [[UIBarButtonItem alloc]
initWithTitle:@"back" style:UIBarButtonItemStyleBordered target:self action:@selector(info_clicked:)];
[toolbar setItems:[NSArray arrayWithObjects:infoButton,nil]];
//Add the toolbar as a subview to the navigation controller.
[self.navigationController.view addSubview:toolbar];
[[self tableView] reloadData];
}
- (void) info_clicked:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
[toolbar removeFromSuperview];
}
И в Swift 3:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//Initialize the toolbar
let toolbar = UIToolbar()
toolbar.barStyle = UIBarStyle.default
//Set the toolbar to fit the width of the app.
toolbar.sizeToFit()
//Caclulate the height of the toolbar
let toolbarHeight = toolbar.frame.size.height
//Get the bounds of the parent view
let rootViewBounds = self.parent?.view.bounds
//Get the height of the parent view.
let rootViewHeight = rootViewBounds?.height
//Get the width of the parent view,
let rootViewWidth = rootViewBounds?.width
//Create a rectangle for the toolbar
let rectArea = CGRect(x: 0, y: rootViewHeight! - toolbarHeight, width: rootViewWidth!, height: toolbarHeight)
//Reposition and resize the receiver
toolbar.frame = rectArea
//Create a button
let infoButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(infoClicked))
toolbar.items = [infoButton]
//Add the toolbar as a subview to the navigation controller.
self.navigationController?.view.addSubview(toolbar)
}
func infoClicked() {
//Handle Click Here
}
Это отлично работает для меня. Я не мог добавить 'UINavigationController', поэтому вручную добавлена панель инструментов. Благодаря! – codingFriend1
Ницца. Я думаю, что это должен быть принятый ответ. Я хотел ** добавить панель инструментов в uitableviewcontroller **, не используя uinavigationcontroller. – soemarko
- 1. Как добавить панель инструментов в UITableViewController
- 2. xcode - Как добавить панель инструментов в UITableViewController
- 3. Как добавить панель инструментов в нижней части UITableViewController в раскадровки?
- 4. Добавить панель инструментов JSQMessagesViewController
- 5. Как я могу добавить панель инструментов в панель инструментов программно?
- 6. Добавить вторую панель инструментов в существующую панель инструментов
- 7. добавить панель инструментов в раздел
- 8. Как добавить uitoolbar в uitableviewcontroller?
- 9. Добавить EditText на панель инструментов
- 10. Добавить виды на панель инструментов
- 11. Добавить панель поиска во вторую секцию uitableviewcontroller
- 12. Панель инструментов - добавить кнопку вверх
- 13. Добавить панель инструментов в datagridview в VB.Net
- 14. Добавить кнопку UITableView Edit на панель инструментов в swift
- 15. Невозможно добавить кнопки в панель инструментов таблицы
- 16. как добавить панель инструментов в listview
- 17. Как добавить панель инструментов в этот макет?
- 18. Можно добавить изображение в панель инструментов?
- 19. добавить панель инструментов в jquery-easyui combogrid
- 20. qooxdoo: добавить панель инструментов в схему сетки?
- 21. Добавить панель инструментов в действие фрагмента
- 22. Добавить панель инструментов в окно CDialog
- 23. Добавить пользовательские WPFControls в панель инструментов автоматически
- 24. Как добавить панель инструментов в этот кадр?
- 25. Как добавить вторую панель инструментов в мэйнфрейм?
- 26. Как добавить изображение в панель инструментов
- 27. Добавить панель инструментов в android app
- 28. Программно добавить UILabel в панель инструментов
- 29. Добавить панель инструментов в tabpanel extjs4.2
- 30. Как добавить панель инструментов в PreferenceActivity
Требуется ли навигационный контроллер? Я хочу добавить ToolBar в TableViewController, который не является частью NavigationController. Нужно ли использовать навигационный контроллер, хотя в нем будет только один вид? – 2011-05-25 04:53:17
@sirjorj Да, 'UINavigationController' требуется для обработки * бесплатной * панели инструментов. Без этого вы должны управлять своим собственным экземпляром представления UIToolbar. – PeyloW
Что делать, если я не хочу помещать кнопки на этой панели инструментов, вместо этого я хочу поместить только изображение в центр, что бы я сделал по-другому? Благодарю. –