0

我有一个这样初始化的按钮>

self.button = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone 
                                                            target:self 
                                                            action:@selector(doAction)];

后来,我给它附加了一个自定义背景,就像那样>

    [self.button  setBackgroundImage:[UIImage imageNamed:@"customNavBar_button_right_enabled"] 
                            forState:UIControlStateNormal 
                          barMetrics:UIBarMetricsDefault];

并将其放在导航栏上。

   [self.navigationItem setRightBarButtonItem:self.button 
                                     animated:NO];

此图像具有固定大小。我希望该按钮具有完全自定义的背景图像,没有使用 UIEdgeInsets 调整大小的“智能”。我不想要任何调整大小。但是由于某种原因,它的行为就像它的 insets 会处于活动状态,并且它被调整为具有更大的宽度,大约图片的中间一半被大大拉伸以提供更宽的按钮。

为什么会这样?我怎样才能防止这种情况发生?

4

1 回答 1

1

The easiest way to achieve a bar button item with a custom image is by:

  1. Drag a UIButton onto the storyboard.
  2. Set the button Type to Custom and set your image for that button.
  3. Drag the button onto your Toolbar.

The storyboard automatically creates a UIBarButtonItem and adds your UIButton as a subview. Or if you do NOT want to use storyboards you could implement the following:

// Initialize the UIButton
UIImage *buttonImage = [UIImage imageNamed:@"buttonImage.png"];
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setImage:buttonImage forState:UIControlStateNormal];
aButton.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);

// Initialize the UIBarButtonItem
UIBarButtonItem aBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:aButton];

// Set the Target and Action for aButton
[aButton addTarget:self action:@selector(aButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

Hope it helps!

EDIT: Do not forget to add the aBarButtonItem to the UIToolbar.

于 2012-10-25T16:46:25.237 回答