导航栏上的自定义UIBarButtonItem图像偏移

问题描述 投票:3回答:2

我想在我的应用程序中使用自己的图像作为动作按钮。我的图像尺寸为30px X 30px。在我的应用程序中,我使用代码:

UIBarButtonItem *heart = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"[email protected]"] style:UIBarButtonItemStyleDone target:self action:@selector(theactionbutton)];
self.navigationItem.rightBarButtonItem = the action;

但是,按钮似乎离左边太远了。我已经附加了两个图像,第一个显示原始操作按钮,第二个显示我的自定义图像,用于比较。有什么想法,为什么它被移到左边?

ios uinavigationcontroller uinavigationbar uibarbuttonitem
2个回答
-1
投票
  1. 创建图像 UIImage *image = [UIImage imageNamed:@"image"];
  2. 创建按钮并设置背景图像和目标操作。

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame= CGRectMake(0.0, 0.0, image.size.width, image.size.height); [button setBackgroundImage:image forState:UIControlStateNormal]; [button addTarget:self action:@selector(theactionbutton) forControlEvents:UIControlEventTouchUpInside];

  1. 创建UIView并添加按钮作为子视图 UIView *view =[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height) ]; [view addSubview:button];
  2. 使用自定义视图创建条形按钮项目并将其设置为导航栏右侧项目 UIBarButtonItem *actionButton = [[UIBarButtonItem alloc] initWithCustomView:view]; self.navigationItem.rightBarButtonItem = actionButton;

注意:@ 2x图像应为双倍大小。如果你的iamgeView是30x30,那么你的Image应该是60X60。如果您有30x30的图像和名称为@ 2x它将被用作15x15所以,使您的图像双倍大小或使用它没有@ 2x


0
投票

您可以使用按钮图像插图,如

barButtonItem.imageInsets = .init(top: 0, left: 10, bottom: 0, right: 10)

© www.soinside.com 2019 - 2024. All rights reserved.