UIToolbar的UIBarButtonItem定制

UIBarButtonSystemItem有10多个类型,但并不能完全满足应用开发需求。
想要弄个设置按钮在右边,首先想到的是图片方式。

无意中发现stack overflow有人提到unicode字符来实现

不使用图片,尝试了各种方法,均无法匹配UIBarButtonSystemItem的效果。

尝试1、

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGFloat toolbarHeight = self.navigationController.toolbar.frame.size.height;
button.frame = CGRectMake(0, 0, toolbarHeight, toolbarHeight);
[button addTarget:self
           action:@selector(btnSettingClicked:)
 forControlEvents:UIControlEventTouchUpInside];
button.titleLabel.font = [UIFont systemFontOfSize:25];
[button setTitleEdgeInsets:UIEdgeInsetsMake(0.0, 21.0, 0.0, 0.0)];
[button setTitle:@"\u2699" forState:UIControlStateNormal];
UIBarButtonItem *settingButton = [[UIBarButtonItem alloc]
                                  initWithCustomView:button];

使用了initWithCustomView方法,这是UIBarButtonItem自由度最高的定制方式。
优点:克服了文字水平偏移,垂直方向自动对其。
缺点:settingButton.style = UIBarButtonItemStylePlain;无效,不能实现高亮状态下的白斑。

尝试2、

UIBarButtonItem *settingButton = [[UIBarButtonItem alloc]
                                      initWithTitle:@"\u2699"
                                      style:UIBarButtonItemStylePlain
                                      target:self
                                      action:@selector(btnSettingClicked:)];
[settingButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:20], UITextAttributeFont, nil] forState:UIControlStateNormal];

使用了initWithTitle方法,代码简洁不少。
优点:可以设置style,实现高亮状态下的白斑。
缺点:UIBarButtonItem的setTitlePositionAdjustment对UIBarButtonItemStylePlain无效,文字会向上偏移2个左右像素,和UIBarButtonSystemItem混用的时候,会看到明显的参差不齐。

结论:使用unicode字符无法完全实现UIBarButtonSystemItem一样的效果。

tip1:
UIBarButtonItem的setTitlePositionAdjustment对UIBarButtonItemStyleBordered有效。

tip2:
UINavigationController中的UIToolbar用下面的方式设置。

[self.navigationController setToolbarHidden:NO animated:NO];
//should set toolbarItems on each individual view controller
[self setToolbarItems:btnArray animated:NO];

标签: iOS

添加新评论