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:
How can I do left Bar Button Item like image? (< Chats part)
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