Reputation: 71
I am using the following code to achieve a navigation bar in my app. (my app was crashing when I used a push segue so I need a modal segue meaning the nav bar is hidden after the modal segue is called)
UINavigationBar *navbar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
//do something like background color, title, etc you self
[self.view addSubview:navbar];
Does any one know any methods I can use with the above code to achieve back button functionality in the nav bar??
Upvotes: 4
Views: 9991
Reputation: 185
Regarding the back button, the proper way is not to create your own.
The UINavigationItem
class has proper support for this:
func setHidesBackButton(_:animated:)
var leftItemsSupplementBackButton: Bool
So, if you want to add a custom button on the left side, just set leftItemsSupplementBackButton
to true
.
Or call
self.navigationItem.setHidesBackButton(false, animated:false)
Upvotes: 1
Reputation: 957
Use below code to add back button on left side
UINavigationBar *navbar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
//do something like background color, title, etc you self
[self.view addSubview:navbar];
UINavigationItem *item = [[UINavigationItem alloc]
init];
navbar.items= @[item];
UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
initWithTitle:@"Back"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(backBtnClicked:)];
item.leftBarButtonItem = backButton;
Upvotes: 4
Reputation: 6882
BackButton is better than LeftButton I think:
UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] init];
[desVC.navigationItem setBackBarButtonItem:backBtn];
Upvotes: 2
Reputation: 23882
Add Back Button With Image :
UIButton *backButton = [[UIButton alloc] initWithFrame: CGRectMake(0, 0, 70.0f, 21.0f)];
UIImage *backImage = [UIImage imageNamed:@"backBtn"];
[backButton setImage:backImage forState:UIControlStateNormal];
[backButton setTitleEdgeInsets:UIEdgeInsetsMake(10.0, 10.0, 10.0, 0.0)];
[backButton setTitle:@"Back" forState:UIControlStateNormal];
[backButton addTarget:self action:@selector(backButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
[negativeSpacer setWidth:-15];
self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacer,backButtonItem,nil];
Upvotes: 1
Reputation: 1220
Use below code to add back button on left side of navigation bar.Add UIBarButtonItem on Navigation bar.
UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
initWithTitle:@"Back"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(backBtnClicked:)];
self.navigationItem.leftBarButtonItem = backButton;
Upvotes: 4