Is it possible to adjust the title of a UIBarButtonItem
inside an UIToolbar
?
I've tried the following lines of code without success:
UIBarButtonItem.appearance().setTitlePositionAdjustment(UIOffset(horizontal: 30, vertical: 30), forBarMetrics: UIBarMetrics.Default)
And this one:
self.setTitlePositionAdjustment(UIOffset(horizontal: 30, vertical: 30), forBarMetrics: UIBarMetrics.Compact)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With