Как программно добавить UIToolbar в UITableViewController?
Я решил использовать UITableViewController
без наконечника. Мне нужен UIToolbar внизу с двумя кнопками. Каков самый простой способ сделать это?
P.S. Я знаю, что я могу легко использовать UIViewController
и добавить UITableView
, но я хочу, чтобы все выглядело последовательно в приложении.
Может кто-нибудь помочь?
Я увидел следующий пример, и я не уверен в его действительности:
(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];
}
Ответы
Ответ 1
Более простая задача - создать проект поверх UINavigationController
. У него уже есть панель инструментов, она просто скрыта по умолчанию. Вы можете открыть его, переключив свойство toolbarHidden
, и ваш контроллер табличного вида сможет использовать его до тех пор, пока он находится в иерархии контроллера навигации.
В делете приложения или в объекте, которому делегирует ваш делегат приложения, создайте контроллер навигации с помощью UITableViewController
в качестве контроллера корневого представления:
- ( void )application: (UIApplication *)application
didFinishLaunchingWithOptions: (NSDictionary *)options
{
MyTableViewController *tableViewController;
UINavigationController *navController;
tableViewController = [[ MyTableViewController alloc ]
initWithStyle: UITableViewStylePlain ];
navController = [[ UINavigationController alloc ]
initWithRootViewController: tableViewController ];
[ tableViewController release ];
/* ensure that the toolbar is visible */
navController.toolbarHidden = NO;
self.navigationController = navController;
[ navController release ];
[ self.window addSubview: self.navigationController.view ];
[ self.window makeKeyAndVisible ];
}
Затем установите элементы панели инструментов в свой MyTableViewController
объект:
- ( void )viewDidLoad
{
UIBarButtonItem *buttonItem;
buttonItem = [[ UIBarButtonItem alloc ] initWithTitle: @"Back"
style: UIBarButtonItemStyleBordered
target: self
action: @selector( goBack: ) ];
self.toolbarItems = [ NSArray arrayWithObject: buttonItem ];
[ buttonItem release ];
/* ... additional setup ... */
}
Ответ 2
Вы также можете просто проверить параметр "Показать панель инструментов" в инспекторе атрибутов NavigationController.
Ответ 3
Вот простой пример, который может помочь
UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *trashItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(deleteMessages)];
UIBarButtonItem *composeItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(composeMail)];
NSArray *toolbarItems = [NSMutableArray arrayWithObjects:spaceItem, trashItem,spaceItem,composeItem,nil];
self.navigationController.toolbarHidden = NO;
[self setToolbarItems:toolbarItems];
Спасибо,
prodeveloper