UIBarButtonItem:setBackgroundVerticalPositionAdjustment无法使用自定义按钮正常工作

时间:2013-05-08 15:48:02

标签: iphone objective-c uibarbuttonitem uiappearance

我有以下代码来自定义UIBarButtonItem(locationButton)的显示:

    UIButton *locationButtonAux = [UIButton buttonWithType:UIButtonTypeCustom];
    [locationButtonAux setFrame:CGRectMake(0, 0, LOCATION_BUTTON_WIDTH, LOCATION_BUTTON_HEIGHT)];
    [locationButtonAux setBackgroundImage:[UIImage imageNamed:@"location_button.png"] forState:UIControlStateNormal];
    [locationButtonAux setBackgroundImage:[UIImage imageNamed:@"location_button.png"] forState:UIControlStateHighlighted];
    [locationButtonAux addTarget:self action:@selector(userLocation) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *locationButton = [[UIBarButtonItem alloc] initWithCustomView:locationButtonAux];
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithTitle:@"title"
                                                              style:UIBarButtonItemStyleDone
                                                             target:nil action:@selector(someMssage)];
    [locationButton setBackgroundVerticalPositionAdjustment:-20.0 forBarMetrics:UIBarMetricsDefault];
    self.navigationItem.rightBarButtonItem = locationButton;

我想将此按钮的位置调整到NavigationBar中,因为我的NavigationBar比正常高(使用Appeareance自定义)。

我正在使用方法setBackgroundVerticalPositionAdjustment,正如您在代码中看到的那样。但是我的UIBarButtonItem根本不起作用,无论我放在哪里,按钮总是显示在靠近栏的底部(快照)。  但是,如果我使用普通样式的普通UIBarButtonItem(我称之为按钮),我可以看到按钮的位置将如何改变-20的偏移量。很奇怪......有什么想法吗?

谢谢!

enter image description here

2 个答案:

答案 0 :(得分:3)

也许这样的事情对你有用:

UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 30)]; //change this frame to counteract for your taller navbar
[rightView addSubview:locationButtonAux];
UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightView];
self.navigationItem.rightBarButtonItem = rightBarButtonItem;

希望这有帮助

答案 1 :(得分:1)

您需要将按钮放在空白视图中并将其放置在该空白视图中。现在,使该视图显示条形按钮项的自定义视图。

你真的不需要这里的按钮,因为这只是一个图像而你没有使用任何按钮功能(你可以附加一个手势识别器来发现水龙头)。所以这是一个使用图像视图的简单解决方案:

UIImageView *locationButtonAux = 
    [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"location_button.png"]];
UIView* v = [[UIView alloc] initWithFrame:locationButtonAux.frame];
[v addSubview:locationButtonAux];
CGRect f = locationButtonAux.frame;
f.origin.y -= 10;
locationButtonAux.frame = f;
UIBarButtonItem *locationButton = [[UIBarButtonItem alloc] initWithCustomView:v];
self.navigationItem.rightBarButtonItem = locationButton;

我省略了手势识别器部分,但您可以轻松查看如何添加它。