0

I want to create a custom left navigation bar button in my code. I can do it with title or only image. When I want the user title and image at the same time, the button is not looking fit.

I tried to add two button. One is for title and another is image but this time there is too much space between the buttons.

I want left navigation button like: enter image description here

How can I do left Bar Button Item like image? (< Chats part)

nodyor90z
  • 312
  • 2
  • 4
  • 13
John
  • 386
  • 1
  • 7
  • 22

2 Answers2

2

First, create a uibutton with title and image, and set the leftbuttonitem of navigationbar to the created unbutton:

//create the uibutton
var button = UIButton.buttonWithType(UIButtonType.Custom) as? UIButton
//Set the image
button?.setImage(UIImage(named: "yourImageName.jpg"), forState: UIControlState.Normal)
//Set the title
button?.setTitle("Yourtitle", forState: UIControlState.Normal)
//Add target
button?.addTarget(self, action:"callMethod", forControlEvents: UIControlEvents.TouchDragInside)
button?.frame=CGRectMake(0, 0, 30, 30)
//Create bar button
var barButton = UIBarButtonItem(customView: button!)
self.navigationItem.leftBarButtonItem = barButton

Then, adjust the position of title and image inside the uibutton using imageEdgeInsets and titleEdgeInsets:

let spacing:CGFloat = 10.0; // the amount of spacing to appear between image and title
tabBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, spacing);
tabBtn.titleEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, 0);

Adjusting the insets here is a bit technical, I just provide a answer you can use directly. For more info, take a look at this post Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

Community
  • 1
  • 1
ilovecomputer
  • 4,238
  • 1
  • 20
  • 33
1

The problem is that you have not set button's imageEdgeInset and titleEdgeInset properly that's why you are getting more space between title and image Try the setting button's imageEdgeInset and titleEdgeInset:

leftBarBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 5)
leftBarBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0)
Ashish Verma
  • 1,776
  • 1
  • 16
  • 27