iPhone UINavigationBar - 设置rightBarButtonItem的宽度和边距

时间:2012-04-25 11:14:27

标签: ios ios5

我有一个按钮的背景图片,尺寸为80x30像素。

我使用下面的代码在我的视图控制器中设置背景,结果如下:

Top and corners are noisy

如您所见,右侧按钮的角落和顶部混乱。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    UIImage *favoriteBtnImgNormal = [[UIImage imageNamed:@"favorite-btn-normal"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 30, 30, 0)];
    UIImage *favoriteBtnImgTouch = [[UIImage imageNamed:@"favorite-btn-touch"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 30, 30, 0)];

    [self.navigationItem.rightBarButtonItem setBackgroundImage:favoriteBtnImgNormal forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [self.navigationItem.rightBarButtonItem setBackgroundImage:favoriteBtnImgTouch forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
    [self.navigationItem.rightBarButtonItem setBackgroundImage:favoriteBtnImgTouch forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
    [self.navigationItem.rightBarButtonItem setTitlePositionAdjustment:UIOffsetMake(-10.0, 0.0) forBarMetrics:UIBarMetricsDefault];
}

请注意,我在单个视图控制器中执行此操作,我使用外观API来设置常规样式。但在这里我想要覆盖整体外观。

如果我只是在没有可调整大小的内容的情况下获取图像,它看起来像这样:

Too large

现在边角都很好,但按钮太大了。

我确定我这样做是错的,所以我需要有人指出我能做些什么来正确缩放按钮?

1 个答案:

答案 0 :(得分:0)

UIImage *image = [UIImage imageNamed:@"YourImage"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

button.bounds = CGRectMake( 0, 0, image.size.width, image.size.height );

[button setImage:image forState:UIControlStateNormal];
[button addTarget:self action:@selector(YourAction) forControlEvents:UIControlEventTouchUpInside];

button.contentEdgeInsets = (UIEdgeInsets){.right=-10};

self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];