Changing vertical position of UIBarButtonItem on i

2019-05-19 23:33发布

问题:

Here is my navigation bar

I had a problem about changing vertical position of Settings UIBarButtonItem on my navigation bar. I would like to move the button item "Settings" down

Here is my code

 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc] initWithTitle:@"Settings" style:UIBarButtonItemStylePlain target:self action:nil];
 self.navItem.rightBarButtonItem = settingsItem; 
    [[UIBarButtonItem appearance] setTitlePositionAdjustment:UIOffsetMake(0,-10) forBarMetrics:UIBarMetricsDefault];

I had tried it again and again. It seemed that it's not work

Could anyone suggest me how to move the button item "Settings" down ?

回答1:

You can easily add a Custom Button to your NavigationBarItem, Here is the way,

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; //create custom Button
    [button setTitle:@"Settings" forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont systemFontOfSize:14.0]];
    [button setTitleColor:[UIColor colorWithRed:179.0/255.0 green:40.0/255.0 blue:18.0/255.0 alpha:1] forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 50, 20); //Button frame
    [button addTarget:self action:@selector(yourCustomSelectorHere) forControlEvents:UIControlEventTouchUpInside]; //Add action method to the button here
    UIView *backButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 63, 33)];
    backButtonView.bounds = CGRectOffset(backButtonView.bounds, -14, -7);
    [backButtonView addSubview:button];
    UIBarButtonItem *barBtnItem = [[UIBarButtonItem alloc]initWithCustomView: backButtonView]; //set button as UIBarButtonItem
    self.navigationItem.rightBarButtonItem = barBtnItem; //set barBtnItem to rightBarButtonItem

By changing backButtonView.bounds values you can change the origin of the Button



回答2:

Cited from apple's documentation on UIAppearance protocol

iOS applies appearance changes when a view enters a window, it doesn’t change the appearance of a view that’s already in a window.

So if your code of setting UIBarButtonItem's appearance is after the navigationItem assignment code. It won't work