在iOS上,我如何水平移动navigationItem.leftBarButtonItem?

时间:2010-09-04 16:45:49

标签: ios uinavigationbar customization

一个cusomized UINavigationBar要求我提供一个自定义的“后退”按钮,我使用navigationItem.leftBarButtonItem = myCustomizedButton,但它的位置是固定的。

有人会如此友好地分享如何将此按钮40像素移到右边?

2 个答案:

答案 0 :(得分:7)

您可以创建一个比图像大40像素的包含视图。 以40像素偏移量添加图像。 将包含视图添加为leftBarButtonItem。

代码如下:

// Create a containing view to position the button
UIView *containingView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, barButtonImage.size.width + 40, barButtonImage.size.height)] autorelease];

// Create a custom button with the image
UIButton *barUIButton = [UIButton buttonWithType:UIButtonTypeCustom];
[barUIButton setImage:barButtonImage forState:UIControlStateNormal];
barUIButton.frame = CGRectMake(40, 0, barButtonImage.size.width, barButtonImage.size.height);
[barUIButton addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

[containingView addSubview:barUIButton];

// Create a container bar button
UIBarButtonItem *containingBarButton = [[[UIBarButtonItem alloc] initWithCustomView:containingView] autorelease];

// Add the container bar button
navigationItem.leftBarButtonItem = containingBarButton;

答案 1 :(得分:1)

您可以在navBar上显示的图片中添加空白区域。我遇到了同样的问题,这是我找到解决它的唯一解决方案。有点棘手,但它有效...