简体   繁体   中英

Custom Trimming Back button text of UINavigationController

Environments :

I'm developing in-app locale changing support for my iOS Apps. It's pretty hard than it sounds, because locales of controls provided with UIKit are tied to iOS Locale.

I could fix almost problems but one thing is remaining for now:

The Problem :

When we push a view controller using an UINavigationController . It will automatically generates back button item with the navigation item title of the previous view controller.

However, what if the title is too long to display as a back button, UINavigationController uses Back as a fallback title. Automatically shorten title(Back) is tied to system locale. And it is my problem.

Can I change this behavior legally?

I made custom UINavigationController and overrided pushViewController:animated:

-(void)pushViewController:(UIViewController *)viewController
                 animated:(BOOL)animated
{
    UINavigationItem* current = self.topViewController.navigationItem;

    if(current.backBarButtonItem == nil){
        current.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:current.title style:UIBarButtonItemStylePlain target:nil action:nil];
    }

    UIBarButtonItem* backItem = current.backBarButtonItem;
    CGFloat width = [backItem.title sizeWithAttributes:@{}].width;

    // Trimming to localized back text
    if(width > 70){
        backItem.title = [[KKCoreLocale shared] localizedStringForKey:@"Back"];
    }

    [super pushViewController:viewController animated:animated];
}

I can't sure this is best solution, However it is legal and works charm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM