Search code examples
iosobjective-cuinavigationbaruinavigationitem

how can I change the horizontal position of BarButtonItem


I can change the y of custom bar button item with setBackgroundVerticalPositionAdjustment, but how can I change the horizontalposition ?

[viewController.navigationItem.rightBarButtonItem setBackgroundVerticalPositionAdjustment:50 forBarMetrics:UIBarMetricsDefault];

Solution

  • You can create bar button with custom view, and in that view you can create your own layout. It can be just simple UIButton, and you can set edgeInsets in UIButton.

    see Customization of UINavigationBar and the back button

    f.e.

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setBackgroundImage:[UIImage imageNamed:@"chk_back.png"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(BackBtn) forControlEvents:UIControlEventTouchUpInside];
    UIView *customView = [[[UIView alloc] initWithFrame:CGRectMake(0,0, 50, 38)] autorelease];
    btn.frame = CGRectMake(10, 3, 30, 32); // where you can set your insets
    [customView addSubview:btn];
        UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithCustomView:customView];
    

    Or you can add some fixedSpace in Bar after or befor your bar item

    UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc] 
                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace 
                                            target:nil 
                                            action:nil];
    [fixedSpace setWidth:20];