水平居中UIToolbar中的所有项目,包括使用UILabel的自定义视图

时间:2013-12-19 04:47:24

标签: ios objective-c ipad uipopovercontroller uitoolbar

我有一个带工具栏和两个按钮的UIPopoverController。在这些系统按钮之间是带有标签的自定义视图。我注意到系统按钮看起来略高于工具栏的中间行。

如果您查看屏幕截图,Cancel+系统按钮看起来比标签更高 - 即使标签是水平居中的。这是iOS 7中的默认外观,因此是“正常”吗?或者我可以使用下面的代码进行一些调整以对齐标签?也许在它的视野中略微向上移动?

enter image description here

我知道这是一件小事,但对我来说看起来很奇怪。

我已经尝试更改自定义视图的框架,但是当它被添加到工具栏时,它似乎会调整它,但它认为合适。我是否应该添加包含工具栏上方标签的视图,而不是包含标签的按钮?

首先我创建了popover控制器:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIViewController *viewController = [[UIViewController alloc] init];
    viewController.view.frame = CGRectMake(0, 0, 200, 200);

    self.popoverController = [[UIPopoverController alloc] initWithContentViewController:viewController];
    UIToolbar *viewToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 200, 39)];
    viewToolbar.backgroundColor = [UIColor grayColor];
    viewToolbar.barStyle = UIBarStyleDefault;

    [self.popoverController.contentViewController.view addSubview:viewToolbar];
    self.popoverController.popoverContentSize = CGSizeMake(200, 200 + 39);

    _toolbar = viewToolbar;
}

然后点击按钮时:

- (IBAction)buttonTapped:(id)sender {
    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelAction:)];
    UIBarButtonItem *separator = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    label.font = [UIFont systemFontOfSize:17];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor blackColor];
    label.text = @"The Title";
    label.textAlignment = NSTextAlignmentCenter;
    [label sizeToFit];

    UIBarButtonItem *title = [[UIBarButtonItem alloc] initWithCustomView:label];
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addAction:)];

    _toolbar.items = @[ cancelButton, separator, title, separator, addButton ];

    [self.popoverController presentPopoverFromRect:self.button.frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:NO];
}

1 个答案:

答案 0 :(得分:1)

一种解决方案是将您的UILabel *标签放入容器中。具有*标签标签的y原点的UIView可能为-2px。然后设置'容器' UIView作为UIBarButtonItem的视图

UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.font = [UIFont systemFontOfSize:17];
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor blackColor];
label.text = @"The Title";
label.textAlignment = NSTextAlignmentCenter;
[label sizeToFit];

UIView *labelContainerView = [[UIView alloc]initWithFrame:label.frame];

//adjust the origin
CGRect labelFrame = label.frame;
labelFrame.origin.y = -2;
label.frame = labelFrame;

[labelContainerView addSubView:label];
UIBarButtonItem *title = [[UIBarButtonItem alloc] initWithCustomView:labelContainerView];