I have a toolbar that is placed at the bottom (correctly). The problem is the button (on a UIBarButtonItem) sits in the center of the entire toolbar.
How can I position this button to the side, but still (vertically) centered with the image? It'd be best with a margin.
So it'd look like
-------------- |. X |. label --------------
The code is:
let customButton: UIButton = UIButton(type: .custom)
customButton.setImage(UIImage(named: "start"), for: .normal)
customButton.setTitle("Start", for: .normal)
customButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12)
customButton.setTitleColor(UIColor.white, for: .normal)
customButton.sizeToFit()
customButton.centerLabelVerticallyWithPadding(spacing: 5)
customButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(startButtonAction(_:))))
iconBar.items = [UIBarButtonItem(customView: customButton)]
Where iconBar
- the toolbar is defined as:
let iconBar: UIToolbar =
{
let view = UIToolbar()
view.translatesAutoresizingMaskIntoConstraints = false
view.barTintColor = UIColor.black
return view
}()
Also I'm using an extension to center the UIButton, then I can add an image (also centered) above it. Here's the extension:
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 = self.titleLabel!.frame.union(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)
}
}
Are you looking for the 'flexible space bar button item' or 'fixed space bar button item'? then you can add a little bit of space to the left and right inside the toolbar and define it's size.
It will look something like this:
let spacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
spacer.width = 10
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments