1. 程式人生 > >導航欄標題文字不居中

導航欄標題文字不居中

出現部分導航欄標題不居中的原因的上一個檢視的title文字過多的情況,引起本頁面的返回按鈕佔居了很多位置將titleview擠到了右邊,要解決這個問題,請在viewdidload中設定前一個檢視的backBarButtonItem。

為了統一設定:利用了https://github.com/steipete/Aspects這個庫注入方法。

方法如下:

 [UIViewController aspect_hookSelector:@selector(viewDidLoad) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> info) {
       
        UIViewController* infoVC = (UIViewController*)info.instance;
        
        
        NSArray *viewControllerArray = [infoVC.navigationController viewControllers];
        
        if (viewControllerArray == nil) {
            return ;
        }
        
        long previousViewControllerIndex = [viewControllerArray indexOfObject:infoVC] - 1;
        UIViewController *previous;
        if (previousViewControllerIndex >= 0 && previousViewControllerIndex < viewControllerArray.count) {
            previous = [viewControllerArray objectAtIndex:previousViewControllerIndex];
            if (previous.title.length < 4){
                return ;
            }
            previous.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]
                                                         initWithTitle:@"xx"
                                                         style:UIBarButtonItemStylePlain
                                                         target:self
                                                         action:nil];
        }
 
    } error:NULL];