Changing vertical position of UIBarButtonItem on iOS 8.2

跟風遠走 提交于 2019-12-08 03:02:05

问题


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



来源:https://stackoverflow.com/questions/29060482/changing-vertical-position-of-uibarbuttonitem-on-ios-8-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!