UIBarButtonItem contains shopping cart and no. of items - swift

I have been struggling with this for hours. I am new to Swift so all I want to do is add an image of a shopping cart and a string to the .rightBarButtonItem and I cannot get it. So far I have this:
let cartIcon = UIBarButtonItem(image: UIImage(named: "shopping_cart_icon"), style: .plain, target: self, action: #selector(didTapCart(_:)))
let cartTotal = UIBarButtonItem(title: "\(cart_total)", style: .plain, target: self, action: #selector(didTapCart(_:)))
navigationItem.rightBarButtonItems = [cartIcon, cartTotal]
But with this, my icon and number is 50px apart! I also tried creating a custom UIView using this:
let view = UIView()
let button = UIButton(type: .system)
button.layer.shadowRadius = 5.0
// autolayout solution
button.translatesAutoresizingMaskIntoConstraints = false
button.widthAnchor.constraint(equalToConstant: 40).isActive = true
button.heightAnchor.constraint(equalToConstant: 40).isActive = true
button.semanticContentAttribute = .forceRightToLeft
button.setImage(UIImage(named: "shopping_cart"), for: .normal)
button.setTitle("\(cartItemArray.count)", for: .normal)
//button.addTarget(self, action: #selector(openDocuments), for: .touchUpInside)
button.sizeToFit()
view.addSubview(button)
view.frame = button.bounds
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: view)
But the icon is massive and when I shrink it, the cart total is again really far away. In both cases, the original image asset is green but it takes on the system blue tint upon building. How do I sort this out?

You are really trying to coerce a very standard iOS UIElement into being something totally different. You need to create you own button and place it where the right bar button item is at. Don't make it a barButtonItem. Just your own Button.
Here is a nice answer showing how to do so:
https://stackoverflow.com/a/31912446/793607

Related

Toolbar doesn't center the button vertically

Can anyone explain to me why Xcode doesn't vertically center the button when you programmatically add the button to the toolbar? When I work with the toolbar added using the Storyboard, the button appears centered horizontally and vertically.
Toolbar added via a storyboard(looks perfect):
Toolbar added via a code:
My code:
self.navigationController?.isToolbarHidden = false
let testButton = UIButton(type: .custom)
testButton.setTitle("Test", for: .normal)
testButton.addTarget(self, action: #selector(test), for: .touchUpInside)
testButton.backgroundColor = .black
testButton.setTitleColor(.white, for: .normal)
testButton.titleLabel?.font = .boldSystemFont(ofSize: 17)
let tb = UIBarButtonItem(customView: testButton)
self.toolbarItems = [tb]

Bar Button Doesn't Appear in PageViewController

I'm learning Swift. I tried adding a button in the UIPageViewController but it didn't show when I run the application. It showed the default back button instead. I tried adding it to a UIViewController and it worked. I already added a navigational bar before inserting the BarButtonItem but it still won't show. Why is it? How do I add the button into the navigation bar of the UIPageViewController?
Expected Navigation Menu Actual Navigation Menu
if you are pushing to pageviewcontroller then try this :-
let myAttribute2 = [ NSForegroundColorAttributeName: UIColor.white
,NSFontAttributeName: UIFont(name: kFontname, size: 20.0)]
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.titleTextAttributes = myAttribute2
self.navigationController?.isNavigationBarHidden = false
self.navigationController?.navigationBar.barTintColor = kNavigationColor
let img = UIImage(named: "menu-icon")
let menuBtn = UIBarButtonItem(image: img, style: .plain, target: self, action: #selector(self.menuAction))
self.navigationItem.leftBarButtonItem = menuBtn

Custom UIButton as Navigation Item Back Button working, but does not show

let btnName = UIButton()
btnName.setImage(UIImage(named: "backIcon"), for: .normal)
btnName.addTarget(self, action: #selector(AddContactViewController.backAction), for: .touchUpInside)
let leftBarButton = UIBarButtonItem()
leftBarButton.customView = btnName
self.navigationItem.leftBarButtonItem = leftBarButton
It works fine, it does what is intended to do. However, on the navigation item it's invisible. But when I click on the area where it should be. It works.
Actually you may have two navigation bars one is of your current class and another is of your previous class.So, you can try by adding below code in your previous class.
override func viewWillDisappear(_ animated: Bool) {
self.navigationController!.navigationBar.isHidden = true
}
I also faced the same problem and it worked for me. May be it will help you.
Everything is ok, except you forgot to set the frame for your button, that's why it's not being shown.
let btnName = UIButton(frame: CGRect(x: 0, y: 0, width: 18, height: 17))
btnName.setImage(UIImage(named: "backIcon"), for: .normal)
btnName.addTarget(self, action: #selector(AddContactViewController.backAction), for: .touchUpInside)
let leftBarButton = UIBarButtonItem()
leftBarButton.customView = btnName
self.navigationItem.leftBarButtonItem = leftBarButton
Rather than hard-coding some frame values, you are better off calling the sizeToFit() method after setting the image, title, etc. I hit this problem today where a custom back button was showing OK on iOS11, but was not visible on iOS9.
btnName.sizeToFit()

Changing navigationItem.rightBarButton isn't resulting in visual changes

For whatever reason my rightBarButton is 1. not going away when I set the rightBarButton to nil and 2. not changing when I set it to another UIBarButtonItem.
I can successfully change the title on the fly so I don't suspect the inherited navigation controller is the problem.
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "Settings"), style: .Plain, target: self, action: nil)
This simply does nothing and the right bar button remains as a button with text "Cancel".
Probably you are have some problem with image: UIImage(named: "Settings"). Check the name of the image or try to use this to fill a UIImageView
EDIT:
this the code that I used to fill a item with an image and act like a button
//set frame
button.frame = CGRectMake(0, 0, 30, 30)
button.addTarget(self, action: #selector(TorchView.showRank(_:)), forControlEvents: .TouchUpInside)
let barButton = UIBarButtonItem(customView: button)
let editButton = UIBarButtonItem(image: UIImage(named: "question"), style: .Plain, target: self, action: #selector(TorchView.tapQuestion))
//assign button to navigationbar
self.navigationItem.rightBarButtonItems = [editButton, barButton]
In this case I am using 2 rightButtons

Why LeftBarButtonItem doesn't appear in the navigationbar in swift

I have two view A and view B.
From view A to view B, I do not use navigation controller, I used performSegueWithIdentifier() and I don't want to use navigation controller to pass view A to view B.
But in the view B, I want to add a leftBarButtonItem in the navigation bar(I have embed a navigation controller for view B) like a back button with a arrow.
In order to achieve 100% same with the system backbitten with arrow. I use NSMutableAttributedString and UIButton. code is below:
let string = "< Retour" as NSString
var attributedString = NSMutableAttributedString(string: string as String)
let ArrowAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont.systemFontOfSize(20)]
let TextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont.systemFontOfSize(10)]
attributedString.addAttributes(ArrowAttributes, range: string.rangeOfString("<"))
attributedString.addAttributes(ArrowAttributes, range: string.rangeOfString(" Retour"))
let backbutton = UIButton(type: .Custom)
backbutton.addTarget(self, action: "back:", forControlEvents: .TouchUpInside)
backbutton.setAttributedTitle(attributedString, forState: UIControlState.Normal)
self.navigationItem.setLeftBarButtonItem(UIBarButtonItem(customView: backbutton), animated: true)
rightBtn = UIBarButtonItem(title: "Ok", style: .Plain, target: self, action: "save:")
But I can not see left button in the navigation bar in view B…why I can not see it in the navigation bar? Why the left button disappear?
Thank you very much.
I have tried the new code for a label, but it doesn't work yet...
let barButtonBackStr = "< Back"
let attributedBarButtonBackStr = NSMutableAttributedString(string: barButtonBackStr as String)
attributedBarButtonBackStr.addAttribute(NSFontAttributeName,
value: UIFont(
name: "AmericanTypewriter-Bold",
size: 18.0)!,
range: NSRange(
location:0,
length:1))
let label = UILabel()
label.attributedText = attributedBarButtonBackStr
label.sizeToFit()
let newBackButton = UIBarButtonItem(customView: label)
self.navigationController!.navigationItem.setLeftBarButtonItem(newBackButton, animated: true)
Thank you
Try a backbutton.sizeToFit() you'll see your button
You create a button but you never set the frame
You can also set the frame directly instead of sizeToFit() method like backbutton.frame = CGRectMake(0, 0, 100, 20)
PS: TextAttributes wasn't used
You must write it to :
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
...
}
Try to set a breakpoint after your UI design and try to launch the Debug View Hierarchy to see if your button exist or is hidden by another object
Next, after you have set your button try to make:
self.navigationController!.navigationItem.leftBarButtonItem.customView.sizeToFit()