I want to make a simple view with a navigation bar and a table view. So I created a subclass of UINavigationController
and I added a UITableView
in it. My is is also the UITableViewDataSource
and UITableViewDelegate
. Now I want to add UIBarButton
in the navigation bar but it doesn't work :
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:[[Translator instance] getTranslation:@"Back"]
style:UIBarButtonItemStylePlain
target:self.parentViewController
action:@selector(dismissFiltersModal:)];
self.navigationItem.backBarButtonItem = anotherButton;
There's no error the view is displayed but not the button. How can I do to display it?
jafar,
as Apple doc suggested you should avoid to subclass UINavigationController
.
This class is not intended for subclassing.
Said this, you could follow these simply steps (some advice for you):
- Create your controller (say
MyController
) that extends UIViewController
and add the table here. Set your controller as the delegate and data source for that table. If you have created by xib you need an outlet for your table view.
[P.S. you could also subclass a UITableViewController
, it has a table view its own]
- In
viewDidLoad
of MyController
customize the navigation bar.
For example
UIBarButtonItem* myButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(someSelector)];
self.navigationItem.leftBarButtonItem = myButton;
You could also customize the title.
For example
self.title = @"Your custom title";
- Somewhere in your code create a
UINavigationController
and add as a root view controller an instance of MyController
.
For example:
MyController* myCtr = // alloc-init here
UINavigationController* nc = [[UINavigationController alloc] initWithRootViewController:myCtr];
The backBarButtonItem
should be set on the previous view controller, not the current one to be displayed. For example, if your you are on view A, navigate to B from it, inside B A's backBarButtonItem
will be displayed, not B's.
If you just want to display an item on the left hand side of the navigation bar, you can use leftBarButtonItem
instead, which will display a normal bar button on that controller. It will be rectangular, not an arrow like normal back buttons though.
How about you try this :
UIButton* backButton = [UIButton buttonWithType:101]; // left-pointing shape!
[backButton addTarget:self action:@selector(dismissFiltersModal:) forControlEvents:UIControlEventTouchUpInside];
[backButton setTitle:@"Back" forState:UIControlStateNormal];
// create button item --
UIBarButtonItem* backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
// add to toolbar
self.navigationItem.leftBarButtonItem = backItem;