导航栏上自定义UIBarButtonItem偏移量

4

我希望在我的应用程序中使用自己的图片作为操作按钮。 我已经将图片大小设置为30像素X 30像素。 在我的应用程序中,我使用以下代码:

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

然而,按钮似乎偏左。我附上两张图片,第一张显示原始操作按钮,第二张显示我的自定义图像,以便比较。有什么想法为什么它会被移动到左边?
2个回答

3
您可以使用按钮图像插入,例如 barButtonItem.imageInsets = .init(top: 0, left: 10, bottom: 0, right: 10) 来调整按钮图像的位置。

-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图像应该是双倍大小。如果您的imageView是30x30,则您的图像应该是60X60。如果您有30x30的图像并将其命名为@2x,则它将被用作15x15,因此请将您的图像放大两倍或不使用@2x。

用 action.png 替换 action@2x.png - Adnan Aftab
那样做把它移动了,但也使它变得很小。 - user717452
好的,我回到 Photoshop 上,将 action.png 调整为 30 x 30,将 action@2x.png 调整为 60 x 60。现在,它又回到了与滑块挤在一起的初始状态。 - user717452
1
这不是好主意...最好设置按钮的框架,您可以清空导航栏中的空白空间,请参见此处: https://dev59.com/R2Mk5IYBdhLWcg3w2RaT#18918378 - Adnan Aftab
谢谢,必须稍微调整一下 negativeSpacer,但那很完美地解决了问题。 - user717452
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接