Adjust vertical position of UIBarButtonItem title inside UIToolbar Adjust vertical position of UIBarButtonItem title inside UIToolbar swift swift

Adjust vertical position of UIBarButtonItem title inside UIToolbar


Offset an UIBarButtonItem (Text!) inside a UIToolBar vertically seems not to work with Xcode 7 (Beta 6).

You are right, according to the docs, this should do it:UIBarButtonItem.appearance().setTitlePositionAdjustment

either globally in AppDelegate:

UIBarButtonItem.appearance().setTitlePositionAdjustment(UIOffset(horizontal: 30, vertical: 30), forBarMetrics: UIBarMetrics.Default)

or locally with the item outlet itself:

(Swift)

self.myBarItem.setTitlePositionAdjustment(UIOffset(horizontal: 30, vertical: 30), forBarMetrics: UIBarMetrics.Default)

(Obj C)

[self.myBarItem setTitlePositionAdjustment:UIOffsetMake(30, 30) forBarMetrics: UIBarMetricsDefault];

Is this a bug with Appearance?


Change the baselineOffset of the text.

let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.someFunction))let attributes = [NSAttributedString.Key.baselineOffset: NSNumber(value: -3)]doneButton.setTitleTextAttributes(attributes, for: .normal)

A negative baselineOffset will shift the title text down, a positive value will shift it up. 0 is the default value.

I tested this on iOS 11.


I was frustrated with this too so I subclassed UIBarButtonItem to work as expected. Taking from this answer I came up with this:

@interface TitleAdjustingBarButtonItem(){    UIView*   _parentView;    UIButton* _button;}@end@implementation TitleAdjustingBarButtonItem-(id) initWithTitle:(NSString *)title style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action{    _button = [[UIButton alloc] init];    [_button setTitle:title forState:UIControlStateNormal];    [_button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];    [_button sizeToFit];    _parentView = [[UIView alloc] initWithFrame:_button.bounds];    [_parentView addSubview:_button];    return [super initWithCustomView:_parentView];}#pragma mark - property setters --(void) setTitlePositionAdjustment:(UIOffset)adjustment forBarMetrics:(UIBarMetrics)barMetrics{    [_button sizeToFit];    _parentView.bounds = CGRectMake(0.0, 0.0, _button.bounds.size.width - (adjustment.horizontal * 2.0), _button.bounds.size.height - (adjustment.vertical * 2.0));}

Admittedly it does not account for the different bar metrics but for default metrics I've gotten this to work pretty well.