I have a UIBarButtonItem
in my UIToolbar
titled
Because UIBarButtonItem inherits from UIBarItem, you can try
- (void)setTitleTextAttributes:(NSDictionary *)attributes
forState:(UIControlState)state
but this is for iOS5 only. For iOS 3/4, you will have to use a custom view.
UIBarButton
haven't property related to change the font. But you can create a button with custom font and then add into UIBarButton. It May be solved your problem
To do this for some UIBarButtonItems
but not all I recommend the following approach.
UIBarButtonItem
subclass. Don't add anything to it - you will only use it as a custom class in the storyboard and for its appearance proxy...UIBarButtonItems
to your subclassUIBarButtonItem
subclass and add the following line to application:didFinishLaunchingWithOptions:
In my case I subclassed UIBarButtonItem
for the sole purpose of bolding the text:
[[BoldBarButtonItem appearance] setTitleTextAttributes:
[NSDictionary dictionaryWithObjectsAndKeys:
[UIFont boldSystemFontOfSize:18.0], NSFontAttributeName,nil]
forState:UIControlStateNormal];
For completion I would like to add this method, still used in Objective-C in 2019. :)
_titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
_titleLabel.text = _titleBarButtonItem.title;
_titleLabel.textColor = UIColor.whiteColor;
_titleLabel.font = [UtilityMethods appFontProDisplayBold:26.0];
[_titleLabel sizeToFit];
UIBarButtonItem *titleLabelItem = [[UIBarButtonItem alloc] initWithCustomView:_titleLabel];
Assuming you want to support iOS4 and earlier, your best bet is to create a bar button using the initWithCustomView:
method and supply your own view which could be something like a UIButton where you can easily customise the font.
You can also drag a UIButton onto a toolbar or navigation bar in Interface Builder if you want to create the button with drag-and-drop instead of programmatically.
Unfortunately this means creating the button background image yourself. There's no way to customise the font of a standard UIBarButtonItem prior to iOS5.
Swift3
buttonName.setAttributedTitle([
NSFontAttributeName : UIFont.systemFontOfSize(18.0),
NSForegroundColorAttributeName : UIColor.red,NSBackgroundColorAttributeName:UIColor.black],
forState: UIControlState.Normal)
swift
barbutton.setTitleTextAttributes([
NSFontAttributeName : UIFont.systemFontOfSize(18.0),
NSForegroundColorAttributeName : UIColor.redColor(),NSBackgroundColorAttributeName:UIColor.blackColor()],
forState: UIControlState.Normal)
Objective-C
[ barbutton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:@"Helvetica-Bold" size:20.0], NSFontAttributeName,
[UIColor redColor], NSForegroundColorAttributeName,[UIColor blackColor],NSBackgroundColorAttributeName,
nil]
forState:UIControlStateNormal];