Mark W
Mark W

Reputation: 3909

best way to truncate all UINavigationBar titles in the app

What would be the best way to enforce a rule that all NavigationItem titles are truncated to a certain number of characters?

What I've looked at doing so far are the following:

subclassing UINavigationController and having all UINavigationControllers in the app inherit from and use this method

@interface MyNavController : UINavigationController {

@end

@implementation MyNavController 

- (void)setTitle:(NSString *)title {

    // do the truncation here, but it's not working
    [super setTitle:myTruncatedTitle];
}

@end

It of course steps into this method anytime a viewcontroller inside this navcontroller calls self.title = ....

But it's not setting this new truncated title to the title that appears in the NavBar.

or I found this solution which involves a category on UINavigationItem and swizzling:

Make all instances of UINavigationBar titles lowercase without subclassing?

are there any other solutions that you can suggest?

Upvotes: 0

Views: 778

Answers (2)

Ashutosh
Ashutosh

Reputation: 2225

In the app delegate's didFinishWithLaunching method, you can write below code:

[[UINavigationBar appearance] setTitleTextAttributes:AttributeDictionary];

Upvotes: 0

Sunny Shah
Sunny Shah

Reputation: 13020

self.navigationItem.titleView=[Utility setTitleOfbar:NSLocalizedString(@"title", nil)];   



+(UIView *)setTitleOfbar:(NSString *)title{
        title = [title substringToIndex: MIN(15, [title length])];

        CGSize size=[[UIScreen mainScreen] bounds ].size;
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(size.width/2-120, 5, 200, 44)];
        [view setBackgroundColor:[UIColor clearColor]];
        UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0,3,200,44)];
        label.text=title;
        label.textAlignment=NSTextAlignmentCenter;
         label.numberOfLines = 0;
        [view addSubview:label];
        return view;
    }

Upvotes: 1

Related Questions