垂直居中的酒吧按钮的标题iOS7

垂直居中的酒吧按钮的标题iOS7

问题描述:

我需要垂直居中的酒吧按钮的标题和按钮本身,你可以从下面的代码中看到,我试图使用setTitlePositionAdjustmentsetBackgroundVerticalPositionAdjustment垂直居中的酒吧按钮的标题iOS7

我预计:

  • 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; 
} 

不使用故事板或碎粒。

尝试使用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]; 
+0

你好,谢谢你的回答。但是,我的代码是做同样的事情,唯一的区别是我使用背景图像,并根据按钮标题长度设置按钮的宽度。问题是我不能在标题内移动标题。 – B1z