This question already has an answer here:
-
UIBarButtonItem with custom view not properly aligned on iOS 7 when used as left or right navigation bar items
15 answers
I am using custom image for navigation bar button.In iOS 6,if we set the left bar button item with button,its x value starts from 10px. But in iOS 7,if we do the same thing,x value of button starts at 20px. Is there any way we shall make it start from 10px as the buttons appearance is not so good with that in iOS 7?
UIBarButtonItems can be initialized using initWithCustomView: method. So you can create some custom view (in your case navigation bar button item with custom image) and initialize bar button item with that custom view. Example:
CustomView *view = [[CustomView alloc] initWithImage:[UIImage imageNamed:@"back.png"]];
UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] initWithCustomView:view];
You can set any frame you want in initWithImage: method of CustomView:
- (id)initWithImage:(UIImage *)image {
self = [super initWithFrame:CGRectMake(0, 0, 50, 44)];
CGRect backArrowFrame;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
backArrowFrame = CGRectMake(-8, 12, 12.5, 20.5);
} else {
backArrowFrame = CGRectMake(-2, 12, 12.5, 20.5);
}
UIButton *imView = [[UIButton alloc] initWithFrame:backArrowFrame];
[imView setContentMode:UIViewContentModeScaleAspectFit];
[imView setBackgroundImage:image forState:UIControlStateNormal];
[imView addTarget:target action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:imView];
return self;
}
In this way it is possible to change frame of UIBarButtonItem.
No, you can't change the UIBarButtonItem
frame. Instead, subclass UINavigationBar
.
Add button as navigation item in ios7 as below
UIButton *btnAdd = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
[btnAdd setContentMode:UIViewContentModeScaleAspectFit];
[btnAdd setBackgroundImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
[btnAdd addTarget:self action:@selector(backButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *btnAdd = [[UIBarButtonItem alloc] initWithCustomView:imView];
self.navigationItem.rightBarButtonItem = btnAdd;