Positioning Navigation Bar buttons in iOS 7 [dupli

2019-06-14 16:47发布

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?

3条回答
神经病院院长
2楼-- · 2019-06-14 17:14

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;
查看更多
叼着烟拽天下
3楼-- · 2019-06-14 17:26

No, you can't change the UIBarButtonItem frame. Instead, subclass UINavigationBar.

查看更多
成全新的幸福
4楼-- · 2019-06-14 17:28

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.

查看更多
登录 后发表回答