简体   繁体   中英

Centre vertically the title of the bar button iOS7

I need to centre vertically the title of the bar button and the button itself, as you can see from the code below, I tried to use setTitlePositionAdjustment and setBackgroundVerticalPositionAdjustment .

I expected:

  • setTitlePositionAdjustment to change the title position, however it changed the position of my background image.
  • setBackgroundVerticalPositionAdjustment to change background image position, however it didnt make any difference

I am a bit confused of this behaviour as the same code worked fine for iOS6. And I am looking for any solution to centre UIButtonItem title vertically. Thank you for your time and help in advance.

 +(UIBarButtonItem *)barButtonItemWithTitle:(NSString *)title Color:(UIColor *)color    Target:(id)target Action:(SEL)action{

  UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:target action:action];
  [barButton setBackgroundImage:[UIImage imageNamed:@"standardButtonBackgroundHighlight"]];
  [barButton setBackgroundVerticalPositionAdjustment:-2.0 forBarMetrics:UIBarMetricsDefault];
  [barButton setTitlePositionAdjustment:UIOffsetMake(1, 2) forBarMetrics:UIBarMetricsDefault];

   NSShadow *shadow = [[NSShadow alloc ]init];
   shadow.shadowColor = [UIColor clearColor];
   NSDictionary *attributes = @{ NSForegroundColorAttributeName : [UIColor redColor],
                                 NSShadowAttributeName: shadow,
                                 NSFontAttributeName : /*pass the font*/ };
   [barButton setTitleTextAttributes:attributes forState:UIControlStateNormal];


return barButton;
}

Not using storyboard or nibs.

Try to play with the frame of UIButton as custom view for UIBarButtonItem.

    *infoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [infoBtn addTarget:self action:@selector(infoClicked:) forControlEvents:UIControlEventTouchUpInside];
    [infoBtn setImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal];
    [infoBtn setImage:[UIImage imageNamed:@"btn-selected.png"] forState:UIControlStateHighlighted];
    [infoBtn setFrame:CGRectMake(0.f, 0.f, 60.f, 20.f)];
    UIBarButtonItem *barBtnItem = [[UIBarButtonItem alloc] initWithCustomView:barBtn];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM