I am trying to make a custom back button using this code:
let back = UIImage(named: "header_backarrow")
let backView = UIImageView(image: back)
let backItem = UIBarButtonItem(customView: backView)
navigationItem.leftBarButtonItem = backItem
I want the navigation item to perform this code:
func dismissManual() {
dismiss(animated: true, completion: nil)
}
I have tried many things like following this Stack Overflow post: Execute action when back bar button of UINavigationController is pressed
I have also tried making it a navigationItem.backBarButtonItem; however, nothing seems to work. Some things show the correct custom image, but do not work as a button; on the other hand, some work as a button, but do not show the correct image.
Does anybody know how I can show the correct image and make the item work as a button? Thanks.
Do it as follows:
override func viewDidLoad() {
super.viewDidLoad()
let back = UIImage(named: "header_backarrow")
let backView = UIImageView(image: back)
backView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(dismissManual))
backView.addGestureRecognizer(tap)
let backItem = UIBarButtonItem(customView: backView)
navigationItem.leftBarButtonItem = backItem
}
#objc func dismissManual() {
print("print----")
// dismiss(animated: true, completion: nil)
}
Add gesture to backView it will work!
It's similiar to this question IOS - Swift - adding target and action to BarButtonItem's customView
Swift 4.1
The issue is that UIImage does not have tap recognition. You will have to add a tap gesture recognizer to your backView.
lazy var singleTap: UITapGestureRecognizer = {
let singleTap = UITapGestureRecognizer(target: self, action: #selector(tapDetected))
singleTap.numberOfTapsRequired = 1
return singleTap
}()
// Actions
#objc func tapDetected() {
dismiss(animated: true, completion: nil)
}
If you show your code, with some screenshots I can give more help if this doesn't solve the issue.
You are creating your UIBarButtonItem incorrectly. You do not need the image view.
Do it as follows:
let back = UIImage(named: "header_backarrow")
let backItem = UIBarButtonItem(image: back, style: .plain, target: self, action: #selector(dismissManual))
navigationItem.leftBarButtonItem = backItem
#objc func dismissManual() {
dismiss(animated: true, completion: nil)
}
Note that the function must be marked with #objc.
Depending on your image and how you want it displayed, you may need to create the image as follows:
let back = UIImage(named: "header_backarrow").withRenderingMode(.alwaysOriginal)
Another option is to create a UIButton with the image and setup to call your dismissManual function. Create the UIBarButtonItem with the button as the custom view.
But it's easier to create a standard UIBarButtonItem when all you have is a simple image or a simple string.
let barButtonItem = UIBarButtonItem(image: UIImage(named: "backImgs"),
style: .plain,
target: self,
action: #selector(menuButtonTapped))
// Adding button to navigation bar (rightBarButtonItem or leftBarButtonItem)
self.navigationItem.rightBarButtonItem = barButtonItem
// Private action
#objc fileprivate func menuButtonTapped() { // body method here }
Check out this, it may help Thanks.
Related
I want customised navigation bar back button title with action.
My Image :
I need back button like this. Here i added text successfully, but not back arrow. Here my code has action for back button.
This is my code
//Custom barButtonItem with custom alert function
self.navigationItem.hidesBackButton = true
let newBackButton = UIBarButtonItem(title: "< Dialer", style: .plain, target: self, action: #selector(back(sender:)))
self.navigationItem.leftBarButtonItem = newBackButton
When i add above code it's getting like this.
func backButtonConfiguration(_ title : String, backImageName : String) {
let backImage : UIImage = UIImage(named: backImageName)!
self.navigationBar.backIndicatorImage = backImage.withRenderingMode(.alwaysTemplate)
self.navigationBar.backIndicatorTransitionMaskImage = backImage
self.navigationBar.backItem?.title = title
}
Update
if we need custom action for back button then we have to add custom BarButtonItem. And if we need bar back button look same as built in back button then we can create custom view and use it it as a bar button item
weak var customView : UIView!
lazy var leftBarButtonView : UIBarButtonItem! = {
let btnBack = UIBarButtonItem(customView: customView)
let gesture = UITapGestureRecognizer(target: self, action: #selector(btnButtonClicked(_:)))
gesture.numberOfTapsRequired = 1
self.customView.addGestureRecognizer(gesture)
self.customView.isUserInteractionEnabled = true
return btnBack
}()
#objc func btnButtonClicked(_ gesture : UITapGestureRecognizer) {
self.navigationController?.popViewController(animated: true)
}
self.navigationItem.leftBarButtonItems = [leftBarButtonView]
I added an extension to UIViewController to add a close button
extension UIViewController {
func addCloseButton() {
let button = UIBarButtonItem(image: #imageLiteral(resourceName: "bar_close"),
landscapeImagePhone: nil,
style: .done,
target: self,
action: #selector(UIViewController.dismiss(animated:completion:)))
navigationItem.leftBarButtonItem = button
}
}
When i tap the barbutton i get a crash directly to AppDelegate.
Any hints? Seems related to the selector.
You can't use dismiss(animated:completion:) as selector here because it takes two arguments bool and closure and bar button action pass args as UIBarButtonItem which cause app crash.
so change your code like this.
extension UIViewController {
func addCloseButton() {
let button = UIBarButtonItem(image: #imageLiteral(resourceName: "rightgreen"),
landscapeImagePhone: nil,
style: .done,
target: self,
action: #selector(onClose))
navigationItem.leftBarButtonItem = button
}
#objc func onClose(){
self.dismiss(animated: true, completion: nil)
}
}
However this question has accepted answer which load extra one method addCloseButton in each and every viewcontroller still posting a answer will going to help someone
NOTE : This example for adding barbutton item automatically and also handle action for pop view controller.
As Protocol extension doesn't provide a to implement selector methods so to get the rid of it I have created this solution.
First thing you need is BaseVC which is subclass of UIViewController and all of your view controller going to be inherited by BaseVC like your class LoginVC:BaseVC ...
now declare protocol
protocol PopableClass {
func popSelf (animated:Bool)
}
extension PopableClass where Self : UIViewController {
func popSelf (animated:Bool) {
self.navigationController?.popViewController(animated: animated)
}
}
In your Base VC add two methods and call setupNavigationBar from viewDidLoad
func setupNavigationBar () {
if self is PopableClass {
let barbuttonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "back"), landscapeImagePhone: #imageLiteral(resourceName: "back"), style: .plain, target: self, action: #selector(popViewController))
self.navigationItem.leftBarButtonItem = barbuttonItem
}
}
//--------------------------------------------------------------------------------
#objc func popViewController () {
if self is PopableClass {
(self as! PopableClass).popSelf(animated: true)
}
}
You did it !!
Now in whatever class you need back button to pop view controller just use like this
class PushedClass: BaseVC,PopableClass
Hope it is helpful
I'm using JSQmessageViewController and trying to programmatically add "back" button & user image on the navigation bar. I'm using the following codes. After running it, there's no "back" button or image. Attached is the screenshot of the simulator. I tested these codes with the normal UIViewController, and they worked.
May I know why they don't work with the JSQmessageViewController? And what should I do to add the "back" button & image on the navigation bar? Thanks a lot!
let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 64))
navigationBar.backgroundColor = UIColor.whiteColor()
navigationBar.delegate = self;
let navigationItem = UINavigationItem()
navigationItem.title = strValue
let leftButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: "back:")
self.navigationItem.leftBarButtonItem = leftButton
let imgButton = UIButton()
imgButton.setImage(image, forState: .Normal)
imgButton.addTarget(self, action: "EditProfile:", forControlEvents: UIControlEvents.TouchDown)
imgButton.frame = CGRectMake(self.view.frame.width - 60, 0, 41, self.view.frame.height)
var rightButton = UIBarButtonItem(customView: imgButton)
self.navigationItem.rightBarButtonItem = rightButton
navigationBar.items = [navigationItem]
self.view.addSubview(navigationBar)
}
So if you use a navigation controller to present your instantiation of the JSQMessagesViewController then the navigation bar should actually already be there. You can just provide it with those buttons and they will be in the correct place. It also seems that you may be doing things in an outdated syntax. Here is the latest Syntax.
Create a function to add your back button.
func addCancelButtonLeft() {
let button = UIBarButtonItem(barButtonSystemItem: .back, target: self, action: #selector(dismissView))
navigationItem.leftBarButtonItem = button
}
Create the action for the button.
func dismissView() {
dismiss(animated: true, completion: nil)
}
Then for your Image you are actually trying to put a button in that title view. Which is fine.
func titleView() {
let imgButton = UIButton()
imgButton.setImage(image, forState: .Normal)
imgButton.addTarget(self, action: #selector(EditProfile), forControlEvents: .touchUpInside)
navigationItem.titleView = imgButton
}
func EditProfile() {
navigationController?.present(EditProfileViewController(), animated: true, completion: nil)
}
let me know if you have more questions and I will see what I can do. Good luck 👍🏼
I have done the following customisation to my embedded UINavigationcontroller. I've done this in the view controller of the view that will show up as first.
However I'm trying to clean it up so that I don't have this all in my UIView class by creating a separate class that will take care of this. The code I'm currently using
self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "navigation.background"), for: .default)
let backButton = UIImage(named: "Back.button")?.withRenderingMode(.alwaysOriginal)
let backButtonHigh = UIImage(named: "Back.button.highlighted")?.withRenderingMode(.alwaysOriginal)
self.navigationController?.navigationBar.backIndicatorImage = backButton
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = backButtonHigh
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
What I've tried to do is extend the UInavigationcontroller in a new class like this
class RSRNavigationController: UINavigationController{
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "navigation.background"), for: .default)
let backButton = UIImage(named: "Back.button")?.withRenderingMode(.alwaysOriginal)
let backButtonHigh = UIImage(named: "Back.button.highlighted")?.withRenderingMode(.alwaysOriginal)
self.navigationController?.navigationBar.backIndicatorImage = backButton
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = backButtonHigh
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}
}
this doesn't work. It will run without problems but it won't actually do anything.
I've also tried to do the following
class RSRNavigationController: UINavigationBar{
override func draw(_ rect: CGRect) {
super.draw(rect)
self.setBackgroundImage(UIImage(named: "navigation.background"), for: .default)
let backButton = UIImage(named: "Back.button")?.withRenderingMode(.alwaysOriginal)
let backButtonHigh = UIImage(named: "Back.button.highlighted")?.withRenderingMode(.alwaysOriginal)
self.backIndicatorImage = backButton
self.backIndicatorTransitionMaskImage = backButtonHigh
//self.backItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}
However I can't seem to set the title for the back button.
Does anyone know how to fix this?
Your problem lies here, when you reference navigationController INSIDE your custom navigationController class
Instead of doing
self.navigationController?.navigationBar.backIndicatorImage = backButton
do this
self.navigationBar.backIndicatorImage = backButton
Reason?
Because when you extend your custom class by UINavigationController, it becomes a navigationController itself. And by doing self.navigationController you are telling your app to look for a navigationController within which your custom navigationCOntroller resides. Ofcourse such a nav controller does not exist because your custom navController is the main or the top navController of the app. So just remove the self.navigationController part from your custom class, the rest of the code that you have written in your viewDidLoad should work good.
If you still have any questions feel free to ask
You do not change these properties in the navigation controller itself, you change it in the viewController that is embedded inside a navigation controller.
These customization has to be done in a parent ViewController of your view controllers.
This Answer has more info:
https://stackoverflow.com/a/16913435/4004429
if you just want to custom the backButton of the navigationBar,you can add this code in your child view controller :
func setupLeftBarItem() -> Void {
let originalImage = UIImage.init(named: "leftBatItem")?.withRenderingMode(.alwaysOriginal)
let leftBarItem = UIBarButtonItem.init(image: originalImage, style: .done, target: self, action: #selector(leftBarButtonItemDidTouch))
navigationItem.leftBarButtonItem = leftBarItem
}
func leftBarButtonItemDidTouch() -> Void {
_ = navigationController?.popViewController(animated: true)
}
I am trying to customize a Navigation bar button item programmatically... I am just having some issues here which I am sure is an easy fix. I want to make it the default Add button for now, but also in the future will want to make the bar button item a custom icon I create. so I guess I would like to know both ways how to programmatically change a navigation bar button to default styles and custom icons...thanks!
override func viewDidAppear(animated: Bool) {
let rightbutton = UIBarButtonItem(title: "+", style: UIBarButtonItemStyle.Plain, target: self, action: "uploadButtonClicked")
navigationItem.rightBarButtonItem = rightbutton
}
Here is how you would do it with the default add button:
let button = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "uploadButtonClicked")
self.navigationItem.rightBarButtonItem = button
Here is how you would programmatically add a custom image:
let customImage = UIImage(named: "customButtonImage")
let customButton = UIBarButtonItem(image: customImage, style: UIBarButtonItemStyle.Plain, target: self, action: "uploadButtonClicked:")
self.navigationItem.rightBarButtonItem = customButton
To perform the segue, you can do this:
#IBAction func uploadButtonClicked(sender: UIBarButtonItem) {
performSegueWithIdentifier("segueIdentifier", sender: self)
}
Or, if you want to go to another storyboard from there, then your IBAction will look like this:
#IBAction func uploadButtonClicked(sender: UIBarButtonItem) {
let storyboard = UIStoryboard(name: "YourStoryboard", bundle: nil)
let nc = storyboard.instantiateInitialViewController() as! UINavigationController
let vc = nc.viewControllers.first as! YourViewController