垂直居中栏按钮iOS7的标题

时间:2014-02-24 15:10:06

标签: ios ios6 ios7

我需要垂直居中条形按钮的标题和按钮本身,如下面的代码所示,我尝试使用setTitlePositionAdjustmentsetBackgroundVerticalPositionAdjustment

我期待:

  • setTitlePositionAdjustment更改标题位置,不过它 改变了我的背景图像的位置。
  • setBackgroundVerticalPositionAdjustment更改背景图片 位置,但它没有任何区别

我对这种行为有点困惑,因为相同的代码适用于iOS6。我正在寻找任何垂直居中UIButtonItem标题的解决方案。感谢您的时间和提前帮助。

 +(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;
}

不使用故事板或笔尖。

1 个答案:

答案 0 :(得分:0)

尝试使用UIButton的框架作为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];