如何在导航栏上的 UIBarButtonItem 内偏移 UIButton 图像?

Posted

技术标签:

【中文标题】如何在导航栏上的 UIBarButtonItem 内偏移 UIButton 图像?【英文标题】:How can i offset UIButton image inside UIBarButtonItem on navBar? 【发布时间】:2011-08-21 19:01:11 【问题描述】:

这是我用来在导航栏上插入自定义 UIBarButtonItem 作为 leftButton 的代码。问题是按钮太靠近左边缘,我无法弄清楚如何在不使用左侧填充的另一个图像的情况下稍微缩进它?

UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
btn.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
[btn setBackgroundImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
self.myBtn = btn;
[btn release];

UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithCustomView:self.myBtn];
self.myBarBtn = barBtn;
self.myBarBtn.imageInsets = UIEdgeInsetsMake(0, 5, 0, 0);
[self.navigationItem setLeftBarButtonItem:self.myBarBtn animated:YES];
[barBtn release];

我尝试过调整框架、edgeInsets,但都没有任何运气。 barButtonItem 仍然太靠近左边缘。有什么办法可以抵消按钮的图像吗?

谢谢

【问题讨论】:

【参考方案1】:
    UIImage *buttonImage = [UIImage imageNamed:@"Close.png"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:buttonImage forState:UIControlStateNormal];
    button.imageEdgeInsets = UIEdgeInsetsMake(0, -40, 0, 0);
    button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);

    [button addTarget:self action:@selector(donePressed:) forControlEvents:UIControlEventTouchUpInside];

    //create a UIBarButtonItem with the button as a custom view
    UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = customBarItem;

【讨论】:

【参考方案2】:

有自定义左右键,语言快捷

let buttonEdit: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
buttonEdit.frame = CGRectMake(0, 0, 40, 40)
buttonEdit.setImage(UIImage(named:"nav-right-Y.png"), forState: UIControlState.Normal)
buttonEdit.addTarget(self, action: "rightNavItemEditClick", forControlEvents: UIControlEvents.TouchUpInside)
var rightBarButtonItemEdit: UIBarButtonItem = UIBarButtonItem(customView: buttonEdit)
self.navigationItem.rightBarButtonItem = rightBarButtonItemEdit

【讨论】:

使用该方法后如何抵消?

以上是关于如何在导航栏上的 UIBarButtonItem 内偏移 UIButton 图像?的主要内容,如果未能解决你的问题,请参考以下文章

需要更改ipad导航栏上的后退按钮名称

自定义 sg 控件和栏上的 UIButton 或 UIBarButtonItem 的背景

ios修改导航栏上返回按钮上的文字,例如把back修改为返回

以编程方式添加到导航栏的UIBarButtonItem无法调用选择器,而添加到工具栏的按钮确实如此

如何解决 UIBarButtonItem 的色调问题?

UIView ExclusiveTouch:UIBarButtonItem 的奇怪行为