Navigation Title background image not working - ios

This my simulator screen shot
import UIKit
class NewsTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
addCustomNavigationBarToView()
}
// This is my custom navigation bar Function
func addCustomNavigationBarToView(){
// Here i create a navigationBar variable
let navigationBar = UINavigationBar(frame: CGRect(x:0, y:0, width: self.view.frame.size.width, height: 100))
let navBackgroundImage:UIImage! = UIImage(named: "BarBa.jpg") self.navigationController?.navigationBar.setBackgroundImage(navBackgroundImage,for: .default)
//i was created navigation item variable and setup an image
let navigationItem = UINavigationItem()
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 220, height: 90 ))
imageView.contentMode = .scaleAspectFit
let image = UIImage(named: "logo.png")
imageView.image = image
navigationItem.titleView = imageView
// Create left and right button for navigation item
let leftButton = UIBarButtonItem(title: "Save", style: UIBarButtonItemStyle.plain, target: self, action: Selector(("saveButtonClicked:")))
navigationItem.leftBarButtonItem = leftButton
//tapping the menu button work
// Assign the navigation item to the navigation bar
navigationBar.items = [navigationItem]
self.view.addSubview(navigationBar)
}
}

In addCustomNavigationBarToView function you have written wrong code:
Your TableViewController don't have any NavigationBar but you are currently setting background Image to self.navigationController.navigationBar :
{ self.navigationController?.navigationBar.setBackgroundImage(navBackgroundImage,for: .default)
}
You need to change your code to:
{
navigationBar.setBackgroundImage(navBackgroundImage,for: .default)
}

Related

How to fit an image in rightbarbuttonitem

I've been trying to put a hamburger button (the three parallel lines) to the right of the titleView in the nav bar, but every time I do, the image I put in covers the entire nav bar and gets rid of the image I have in titleView.
If I select a default image in the storyboard editor it will appear on the right side of the nav bar without any problems, but as soon as I select the hamburger button in the storyboard editor I get the same problem as before. I've tried with multiple different images and I've changed up the code a little bit with no success. Is there a way to resize the image I'm using so it will fit in the nav bar properly or is there just something wrong with my code?
Here is my code from viewController.swift below:
override func viewDidAppear(_ animated: Bool) {
let nav = self.navigationController?.navigationBar
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
imageView.contentMode = .scaleAspectFit
let titleImage = UIImage(named: "logowhitecircle")
imageView.image = titleImage
navigationItem.titleView = imageView
let menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
menuButton.contentMode = .scaleAspectFit
let menuImage = UIImage(named: "hamburgericon")
menuButton.setImage(menuImage, for: .normal)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: menuButton)
You need to set image size in the image assets like 3x = 84px, 2x=56px, 1x = 28px,
see the apple document for more info: https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/custom-icons/
let menuButton = UIBarButtonItem(image: UIImage(named: "logowhitecircle"), style: .plain, target: self, action: #selector(menuButtonTapped(_:)))
self.navigationItem.rightBarButtonItem = menuBu
tton
Try Using below code:
let imageBurger = UIImage(named: "hamburgericon")!
let btnLeftMenu = UIButton(type: .system)
btnLeftMenu.bounds = CGRect(x: 10, y: 0, width: imageBurger.size.width, height: imageBurger.size.height)
btnLeftMenu.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
btnLeftMenu.setImage(imageBurger, for: UIControl.State())
btnLeftMenu.setTitle(title, for: .normal)
let leftButton = UIBarButtonItem(customView: btnLeftMenu)
self.navigationItem.leftBarButtonItem = leftButton
Try this module FFBadgedBarButtonItem it's easy to use module, here is the documenataion Link
Below is my code how to implement it!
let image = UIImage(named: "yourImage")
let finalImage = resizeImage(image: image!, newWidth: 30)
navigationItem.rightBarButtonItem = FFBadgedBarButtonItem(image: finalImage, target: self, action: #selector(rightButtonTouched))
And here is the calling function
#objc func rightButtonTouched() {
// what event you need to perfom by clicking on this button
}
You need to create Bridging Header to work with this Obj-C module.
: D
Try this:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//create a new button
let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
//set image for button
button.setImage(UIImage(named: "hamburgericon"), forState: UIControlState.Normal)
//add function for button
button.addTarget(self, action: "customButtonPressed", forControlEvents: UIControlEvents.TouchUpInside)
//set frame
button.frame = CGRectMake(0, 0, 40, 40)
let barButton = UIBarButtonItem(customView: button)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = barButton
}
//This method will call when you press button.
func customButtonPressed() {
println("button pressed")
}
}

how to set the image position and size of image that inserted in navigation bar?

actually I don't know the correct way how to make an image inside the navigation bar like this, either using navigation controller or by using custom view by myself
I need to insert these 2 image as bar button and image title
so I tried to use navigation controller and insert an image in viewDidLoad like the code below:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// insert image title
let aspectRatio : CGFloat = 0.25
let widthOfImageHeader = view.frame.width * 0.5
let heightOfImageHeader = widthOfImageHeader * aspectRatio
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: widthOfImageHeader, height: heightOfImageHeader))
imageView.contentMode = .scaleAspectFit
let image = UIImage(named: "testImage2")
imageView.image = image
navigationItem.titleView = imageView
// set bar button image
//create a new button
let button = UIButton(type: .custom)
//set image for button
button.setImage(UIImage(named: "hamburgerIcon"), for: .normal)
//set frame
button.frame = CGRect(x: 0, y: 0, width: 53, height: 51)
let barButton = UIBarButtonItem(customView: button)
//assign button to navigationbar
self.navigationItem.leftBarButtonItem = barButton
}
}
but the result is like the image below:
the position of image title is not exactly in the center for iPhone 5s and bar button seems a little bit off in the right.
and if I assign the image right bar button, using
/
/create a left button
let button = UIButton(type: .custom)
//set image for button
button.setImage(UIImage(named: "hamburgerIcon"), for: .normal)
//set frame
button.frame = CGRect(x: 0, y: 0, width: 53, height: 51)
let barButton = UIBarButtonItem(customView: button)
//assign button to navigationbar
self.navigationItem.leftBarButtonItem = barButton
//create a right button
let button2 = UIButton(type: .custom)
//set image for button
button2.setImage(UIImage(named: "backButton"), for: .normal)
//set frame
button2.frame = CGRect(x: 0, y: 0, width: 53, height: 51)
let barRightButton = UIBarButtonItem(customView: button)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = barRightButton
the result is even weirder
one of the button dissapears, the hamburger icon that should be on the left, now in the right
it will be far easier if I use custom view, but...is it weird if I use custom view that use like navigation bar? I am new in iOS Developer. Thanks in advance
Okay so here's what I usually do in a project with such kind of requirements (image at the navBar's title, and custom bar button items).
To answer first your question, you can actually do whatever you want.
Have indeed a custom view while having your viewController embedded inside a UINavigationController. But be sure to hide the navBar.
Have a visible navBar and viewContorller embedded in UINavigationController.
The ideal way for me is the latter.
The sample project below was made using my own old framework: https://github.com/glennposadas/gpkit-ios
You can copy any pieces of codes from that framework, modify/rename everything on it, and put in your production project.
If you want the result below, here's how I do it:
import GPKit
import UIKit
class ViewController: UIViewController {
// MARK: - Properties
internal lazy var button_Close: UIButton = {
let button = UIButton(type: .custom)
button.setImage(UIImage(named: "ham"), for: .normal)
button.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: -30, bottom: 0, right: 0)
//button.addTarget(self, action: #selector(hamburger(_:)), for: .touchUpInside)
return button
}()
// MARK: - Functions
// MARK: Overrides
override func viewDidLoad() {
super.viewDidLoad()
GPLog(classSender: self, log: "viewDidLoad!")
// Title View Test: -
let navBarImage = UIImage(named: "ic_logo_navbar")!
self.setNavBarTitleWithFeedback(image: navBarImage, navBarTintColor: .white)
self.makeNavBarColor(color: UIColor.colorWithRGBHex(0x332F39), itemsTintColor: .white)
// Barbutton
let barButton = UIBarButtonItem(customView: self.button_Close)
self.button_Close.frame = CGRect(x: 0, y: 0, width: 55.0, height: 44.0)
let negativeSpacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.fixedSpace, target: nil, action: nil)
if #available(iOS 11.0, *) {
negativeSpacer.width = -30
}
self.navigationItem.leftBarButtonItems = [negativeSpacer, barButton]
}
}
extension ViewController: GPTitleViewDelegate {
func gpTitleView(userDidTapTitleView gpTitleView: GPTitleView) {
GPLog(classSender: self, log: "userDidTapTitleView🌈")
}
func gpTitleView(userDidFinishLongPress gpTitleView: GPTitleView) {
GPLog(classSender: self, log: "userDidFinishLongPress🌺")
}
}
Result:
I don't have your hex color, so it looks ugly.
I hope thish elps.

Need to set logo in left side of Navigation bar in AppDelegate

I am working on a swift project.In that i need the logo to be shown in left side of navigation bar and would like to make it globally in AppDelegate. But self.navigationitem is not detected in Appdelegate?Any Help would be appreciated as its my first project in swift.
UINavigationBar.appearance().barTintColor = Constants.templatecolor
let logoImage = UIImage.init(named: "logoImage")
let logoImageView = UIImageView.init(image: logoImage)
logoImageView.frame = CGRect(x: -40, y: 0, width: 150, height: 25)
logoImageView.contentMode = .scaleAspectFit
let imageItem = UIBarButtonItem.init(customView: logoImageView)
let negativeSpacer = UIBarButtonItem.init(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
negativeSpacer.width = -25
UINavigationItem.setLeftBarButtonItems(negativeSpacer, imageItem)
You can't set the Navigation item in AppDelegate. Navigation item is the property of UIViewController or UINavigationController and you set the UINavigationItem for each ViewControllers.
If all that you wanna achieve is setting the navigation title for all screens declare a base class call it as BaseViewController n in viewDidLoad of BaseViewController set the navigation item
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let logoImage = UIImage.init(named: "close")
let logoImageView = UIImageView.init(image: logoImage)
logoImageView.frame = CGRect(x: -40, y: 0, width: 150, height: 25)
logoImageView.contentMode = .scaleAspectFit
let imageItem = UIBarButtonItem.init(customView: logoImageView)
let negativeSpacer = UIBarButtonItem.init(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
negativeSpacer.width = -25
self.navigationItem.leftBarButtonItems = [negativeSpacer,imageItem]
// Do any additional setup after loading the view.
}
}
Now every single viewController in your project can extend from BaseViewController
class ViewController: BaseViewController {
...
override func viewDidLoad() {
super.viewDidLoad()
}
}
Make sure you call super.viewDidLoad in viewDidLoad
Hope it helps
Please change x position of logoImageView while setting its frame.
You are sets it's value as -40 might be because of that you are not able to see that logoImage.
Change it's x position to 0.

Swift: How do I create a custom UINavigationBar and add a custom back button?

I am trying to create a custom navigationBar.
I am hiding the original navigationBar in viewWillAppear like so:
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = true
}
I am subclassing UINavigationBar like so:
let navBar: UINavigationBar = {
let view = UINavigationBar()
view.backgroundColor = .clear
view.isTranslucent = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
In viewDidLoad I am calling setupNavBar():
func setupNavBar() {
view.addSubview(navBar)
self.navBar.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 80)
let backButton = UIBarButtonItem(image: UIImage(named:"backThick"), style: .plain, target: self, action: #selector(popControllerOffStack))
}
The problem is that backButton is added to the original navigationBar that is being hidden. This makes me think I am incorrectly creating the navigationBar. How do I add the button to navBar?
Updated Code (still not working):
class CustomNavBar: UINavigationBar {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .red
}
}
// In the viewController
let navBar = CustomNavBar()
override func viewDidLoad() {
super.viewDidLoad()
setupNavBar()
}
func setupNavBar() {
view.addSubview(navBar)
navBar.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 80)
let backButton = UIBarButtonItem(image: UIImage(named:"backThick"), style: .plain, target: self, action: #selector(popControllerOffStack))
self.navigationItem.leftBarButtonItem = backButton
}
The button is being added to the original navigationBar.
You are not subclassing UINavigationBar. Rather, you are creating a new instance of UINavigationBar and modifying its properties inside a computed variable. This means each time you access navBar, you are initializing a new UINavigationBar object.
To create a subclass:
class MyCustomNavigationBar: UINavigationBar {
// Set properties in here after initialization
}
Once you have a proper subclass created, You can initialize an instance like so:
var navBar = MyCustomNavigationBar()
Finally, add your button to the navigation bar:
let backButton = UIBarButtonItem(image: UIImage(named:"backThick"), style: .plain, target: self, action: #selector(popControllerOffStack))
// Assuming 'self' is an instance of UINavigationController()
self.navigationItem.leftBarButtonItem = backButton
See the official Swift Programming Language Guide on Inheritance.
Swift 3.0
You can set custom Back button as like below
self.navigationItem.hidesBackButton = true
let backButton = UIBarButtonItem(image: UIImage(named: "image_name"), style: .plain, target: self, action: #selector(Class.methodName))
backButton.tintColor = UIColor.white
self.navigationItem.leftBarButtonItem = backButton
Also you can try below code:
let btnLeftMenu: UIButton = UIButton()
btnLeftMenu.setImage(UIImage(named: "image_name"), for:UIControlState())
btnLeftMenu.addTarget(self, action: #selector(moveImage), for:UIControlEvents.touchUpInside)
btnLeftMenu.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
let barButton = UIBarButtonItem(customView: btnLeftMenu)
self.navigationItem.leftBarButtonItem = barButton*

How can i fix this error?? error is cannot assign to the property "target is a method"

//This is my custom navigation function
func addSlideMenuButton()
// This is my custom navigation bar
let navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width,height: 104))
let backgroundImage = UIImage(named: "BarBa")?.resizableImage(withCapInsets: UIEdgeInsetsMake(0, 15, 0, 15), resizingMode: UIImageResizingMode.stretch)
UINavigationBar.appearance().setBackgroundImage(backgroundImage, for: .default)
// Create a navigation item with a title
let navigationItem = UINavigationItem()
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 70, height: 90 ))
imageView.contentMode = .scaleAspectFit
let image = UIImage(named: "logo.png")
imageView.image = image
navigationItem.titleView = imageView
let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "sidebar.png"), for: UIControlState.normal)
button.addTarget(self, action:#selector(NewsTableViewController.callMethod), for: UIControlEvents.touchUpInside)
button.frame = CGRect.init(x: 0, y: 0, width: 70, height: 80)
let customBarItem = UIBarButtonItem(customView: button)
self.navigationItem.leftBarButtonItem = customBarItem;
navigationBar.items = [navigationItem]
// Make the navigation bar a subview of the current view controller
self.view.addSubview(navigationBar)
//tapping the menu button work
// Here revealViewController is a objective C class
if self.revealViewController() != nil {
button.target = self.revealViewController()
button.action = #selector(SWRevealViewController.revealToggle(_:)) // in this 2 line i got error cannot assign to the property "target is a method"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
// for set customiz width
self.revealViewController().rearViewRevealWidth = 250
}
// Assign the navigation item to the navigation bar
navigationBar.items = [navigationItem]
self.view.addSubview(navigationBar)
}
I guess this is what you are looking for and target & action are methods. you are treating it like properties. and i'm guessing self.revealViewController() returning SWRevealViewController instance.
button.addTarget(self.revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:)), for: .touchUpInside)
Working code
menuButton.addTarget(self.revealViewController(), action:
#selector(SWRevealViewController.revealToggle(_:)), for: .touchUpInside)
you are not using a bar button item, SWRevealController action and target work with bar button not simple button

Resources