#import
@interface UINavigationItem (correct_offset)
- (void)addLeftBarButtonItem:(UIBarButtonItem *)leftBarButtonItem;
- (void)addRightBarButtonItem:(UIBarButtonItem *)rightBarButtonItem;
@end
#import UINavigationItem+correct_offset.h
#define ios7 ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0?YES:NO)
@implementation UINavigationItem (correct_offset)
- (void)addLeftBarButtonItem:(UIBarButtonItem *)leftBarButtonItem
{
if (ios7) {
// Add a spacer on when running lower than iOS 7.0
UIBarButtonItem *negativeSpacer = [[UIBarButtonItemalloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
target:nil action:nil];
negativeSpacer.width = -20;
[self setLeftBarButtonItems:[NSArrayarrayWithObjects:negativeSpacer, leftBarButtonItem,nil]];
} else {
// Just set the UIBarButtonItem as you would normally
[self setLeftBarButtonItem:leftBarButtonItem];
}
}
- (void)addRightBarButtonItem:(UIBarButtonItem *)rightBarButtonItem
{
if (ios7) {
// Add a spacer on when running lower than iOS 7.0
UIBarButtonItem *negativeSpacer = [[UIBarButtonItemalloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
target:nilaction:nil];
negativeSpacer.width = 10;
[self setRightBarButtonItems:[NSArrayarrayWithObjects:negativeSpacer, rightBarButtonItem,nil]];
} else {
// Just set the UIBarButtonItem as you would normally
[self setRightBarButtonItem:rightBarButtonItem];
}
}
@end
在要設置返回按鈕的UIViewController中按照如下使用。
[self.navigationItemaddLeftBarButtonItem:[self creatBarItemWithAction:@selector(dismiss)]];
creatBarItemWithAction是我自己寫的一個方法。
/**
* 退出視圖。
*/
-(void)dismiss
{
[selfdismissViewControllerAnimated:YEScompletion:nil];
}
/**
* 創建一個UIBarButtonItem
*
* @param _action action
*
* @return UIBarButtonItem
*/
-(UIBarButtonItem*)creatBarItemWithAction:(SEL)_action{
UIButton* button = [UIButtonbuttonWithType:UIButtonTypeCustom];
[button setImage:[UIImageimageNamed:@backButton.png]forState:UIControlStateNormal];
[button setFrame:CGRectMake(0,0,40, 40)];
[button addTarget:selfaction:_action forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem* item = [[UIBarButtonItemalloc] initWithCustomView:button] ;
return item;
}
在要設置返回按鈕的UIViewController中按照如下使用。
self.navigationItem.leftBarButtonItem = [selfcreatBarItemWithAction:@selector(dismiss)solutiontwo:2];
-(UIBarButtonItem*)creatBarItemWithAction:(SEL)_action solutiontwo:(NSInteger)index{
UIButton* button = [UIButtonbuttonWithType:UIButtonTypeCustom];
[button setImage:[UIImageimageNamed:@backButton.png]forState:UIControlStateNormal];
[button setFrame:CGRectMake(0,0,40, 40)];
if (ios7) {
[button setImageEdgeInsets:UIEdgeInsetsMake(0, -30,0, 0)];
}
else
{
[button setImageEdgeInsets:UIEdgeInsetsMake(0,0, 0,0)];
}
[button addTarget:selfaction:_action forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem* item = [[UIBarButtonItemalloc] initWithCustomView:button] ;
return item;
}