4

我有以下代码来自定义 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 的偏移量。很奇怪......有什么想法吗?

谢谢!

在此处输入图像描述

4

2 回答 2

3

Perhaps something like this would work for you:

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;

Hope this helps

于 2013-05-08T15:57:41.537 回答
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;

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

于 2013-05-08T16:38:47.110 回答