2

I want to add a text under the icon in toolbar.

Now I can just add or title, or image.

Can I make that I will have image and under the image label of text?

I did add label in the bottom of image, but how can I cantralize it like I do it with images by Flexible Space Bar Button Item?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Orkhan Alizade
  • 7,379
  • 14
  • 40
  • 79

1 Answers1

2

First you need to create an extension of UIButton, this post give the solution. Then, you can embed a UIButton as a custom view inside your UIBarButtonItem

extension UIButton {
    func centerLabelVerticallyWithPadding(spacing:CGFloat) {
        // update positioning of image and title
        let imageSize = self.imageView!.frame.size
        self.titleEdgeInsets = UIEdgeInsets(top:0,
            left:-imageSize.width,
            bottom:-(imageSize.height + spacing),
            right:0)
        let titleSize = self.titleLabel!.frame.size
        self.imageEdgeInsets = UIEdgeInsets(top:-(titleSize.height + spacing),
            left:0,
            bottom: 0,
            right:-titleSize.width)

        // reset contentInset, so intrinsicContentSize() is still accurate
        let trueContentSize = CGRectUnion(self.titleLabel!.frame, self.imageView!.frame).size
        let oldContentSize = self.intrinsicContentSize()
        let heightDelta = trueContentSize.height - oldContentSize.height
        let widthDelta = trueContentSize.width - oldContentSize.width
        self.contentEdgeInsets = UIEdgeInsets(top:heightDelta/2.0,
            left:widthDelta/2.0,
            bottom:heightDelta/2.0,
            right:widthDelta/2.0)
    }
}


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let customButton : UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
        customButton.setImage((UIImage(named: "Image")), forState:UIControlState.Normal)
        customButton.setTitle("Button", forState: UIControlState.Normal)
        customButton.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
        customButton.sizeToFit()
        customButton.centerLabelVerticallyWithPadding(5)
        let customBarButtonItem = UIBarButtonItem(customView: customButton as UIView)
        self.navigationItem.rightBarButtonItem = customBarButtonItem;

    }
}
Community
  • 1
  • 1
agy
  • 2,804
  • 2
  • 15
  • 22
  • This should be marked as an an accepted answer. It works great for me once I set the title size to 10 pt font and set the padding to 0 - although that might due to my images and bar height. – stepheaw Apr 17 '20 at 14:11