我想在我的应用程序中使用自己的图像作为动作按钮。我的图像尺寸为30px X 30px。在我的应用程序中,我使用代码:
UIBarButtonItem *heart = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"[email protected]"] style:UIBarButtonItemStyleDone target:self action:@selector(theactionbutton)];
self.navigationItem.rightBarButtonItem = the action;
但是,按钮似乎离左边太远了。我已经附加了两个图像,第一个显示原始操作按钮,第二个显示我的自定义图像,用于比较。有什么想法,为什么它被移到左边?
UIImage *image = [UIImage imageNamed:@"image"];
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];
UIView *view =[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height) ];
[view addSubview:button];
UIBarButtonItem *actionButton = [[UIBarButtonItem alloc] initWithCustomView:view];
self.navigationItem.rightBarButtonItem = actionButton;
注意:@ 2x图像应为双倍大小。如果你的iamgeView是30x30,那么你的Image应该是60X60。如果您有30x30的图像和名称为@ 2x它将被用作15x15所以,使您的图像双倍大小或使用它没有@ 2x
您可以使用按钮图像插图,如
barButtonItem.imageInsets = .init(top: 0, left: 10, bottom: 0, right: 10)