修复iOS7下leftBarButtonItem位置相比之前版本靠右的问题

Xcode升级到5.0版本之后,在iOS7下,通过 leftBarButtonItem 设定的左导航栏按钮会出现明显的靠右偏移的情况,就像下面图片这样:

Ios7 leftbar button item

这样的效果看起来是比较别扭的,为了让iOS7下面看起来跟以前一样,就需要针对iOS7特别处理一下了:

    UIButton * backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, 60, 44);
    [backButton setImage:[UIImage imageNamed:@"back_btn_bg.png"] forState:UIControlStateNormal];
    [backButton setTitle:@"Back" forState:UIControlStateNormal];
    [backButton setTitleEdgeInsets:UIEdgeInsetsMake(-1, -55, 0, 0)];
    [backButton.titleLabel setFont:[UIFont boldSystemFontOfSize:14.0]];
    [backButton setTitleColor:[UIColor colorWithRed:233.0/255.0 green:220.0/255.0 blue:207.0/255.0 alpha:1.0]
                     forState:UIControlStateNormal];
    UIBarButtonItem *backNavigationItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];

    // 调整 leftBarButtonItem 在 iOS7 下面的位置
    if(([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0?20:0)){
      UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                         initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                         target:nil action:nil];
      negativeSpacer.width = -10;
      self.navigationItem.leftBarButtonItems = @[negativeSpacer, backNavigationItem];
    }else
      self.navigationItem.leftBarButtonItem = backNavigationItem;

这样就可以了,示例程序代码下载请戳 —> Ios7LeftBarButtonItem.zip

This entry was posted in iOS and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Verify Code   If you cannot see the CheckCode image,please refresh the page again!