Reputation: 7569
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
?
Upvotes: 2
Views: 2533
Reputation: 2854
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;
}
}
Upvotes: 2