UIToolbar左右填充最初为负

时间:2015-01-21 20:00:25

标签: ios objective-c iphone uikit uitoolbar

我正在努力应对UIToolbar在iOS7 + iPhone应用程序中的奇怪行为。

以下是我创建它的方式:

//toolbar
self.bottomToolbar=[[UIToolbar alloc] initWithFrame:CGRectMake(0.0, self.view.bounds.size.height-44.0, self.view.bounds.size.width, 44.0)];
self.bottomToolbar.autoresizingMask=(UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth);
[MKUIHelper toolbar:self.bottomToolbar setBarStyle:MKBarStyleWhite];
self.bottomToolbar.items=@[];
[self.view addSubview:self.bottomToolbar];

当我需要更新它时,我正在调用(实际上只更新其中一个项目,但这没关系):

-(void)updateToolbar
{
    UIBarButtonItem *doneBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"done" style:UIBarButtonItemStylePlain target:self action:@selector(backButtonDidPress:)];
    doneBarButtonItem.tintColor=MK_Color_Green;
    UIBarButtonItem *clearBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"clear" style:UIBarButtonItemStylePlain target:self action:@selector(clearButtonDidPress:)];
    clearBarButtonItem.tintColor=MK_Color_Pink;
    UIBarButtonItem *spaceBetweenBackAndQuantity=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *spaceBetweenQuantityAndClear=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];        

    UIBarButtonItem *quantityItem=[self quantityBarButtonItem];
    self.bottomToolbar.items=[NSArray arrayWithObjects:doneBarButtonItem, spaceBetweenBackAndQuantity, quantityItem, spaceBetweenQuantityAndClear, clearBarButtonItem, nil];

    [self.rootViewController reloadToolbar];
}

使用UIBarButtonItem创建的initWithTitle:..个对象都以某种方式具有负的左右填充。可以通过向items数组的两侧添加额外的固定空间类型UIBarButtonItem来粗略地修复它。换句话说:使用固定空间类型UIBarButtonItems补偿奇怪的初始左右填充。

请帮帮我一个人。是什么原因引起这种奇怪的我该如何摆脱这种奇怪的填充物?

以下是它的样子:

strange initial toolbar negative padding

1 个答案:

答案 0 :(得分:0)

如果将barButtons的宽度设置为正确的宽度,则可以解决此问题。

- (UIBarButtonItem *)barButtonWithTitle:(NSString *)title action:(SEL)action {

    UIBarButtonItem *barButtonItem = [[[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:self action:action] autorelease];


    UIButton *button = [UIButton buttonWithType: UIButtonTypeCustom];
    [button setTitle:title forState: UIControlStateNormal];
    [button sizeToFit];
    CGSize size = button.bounds.size;

    [barButtonItem setWidth:size.width];

    return barButtonItem;
}