即使图像大小没有改变,setImage方法也会改变UIBarButtonItem的宽度

时间:2013-03-01 01:42:22

标签: iphone ios objective-c uibarbuttonitem

我想在导航栏中添加一个“书签”按钮作为rightBarButtonItem

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Add bookmark button
    UIBarButtonItem *bookmarkBarButton = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:self action:@selector(bookmark:)];
    [bookmarkBarButton setImage:[UIImage imageNamed:@"greyBookmark.png"]];
    [self.navigationItem setRightBarButtonItem:bookmarkBarButton];
    bookmarkBarButton.tintColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:0.9f];
    b_bookmarked = false;
}

// Will call this method when the bookmark button is pressed
- (IBAction)bookmark:(id)sender
{
    // Toggle color of bookmark icon on button
    if ( (b_bookmarked = !b_bookmarked) )
    {
        [self.navigationItem.rightBarButtonItem setImage:[UIImage imageNamed:@"blueBookmark.png"]];
    }
    else
    {
        [self.navigationItem.rightBarButtonItem setImage:[UIImage imageNamed:@"greyBookmark.png"]];
    }

    // Save bookmark

}

greyBookmark.png和blueBookmark.png都有10x26大小。视图出现时,按钮看起来变窄。但是,当我单击此按钮时,按钮变宽,图像仍然会发生变化。 在bookmark:方法中调用setImage方法时,宽度会更改(恢复为默认大小)。我试图通过调用[navigationItem.rightBarButtonItem setWidth:]显式设置宽度 - 也没有帮助。在此之前,根据文档,width属性设置为0,按钮应根据图像大小调整大小。

我希望rightBarButtonItem具有const宽度。 有没有理由在第二次调用setImage后它变得更宽?

1 个答案:

答案 0 :(得分:6)

UIImage *myImage = [UIImage imageNamed:@"greyBookmark.png"];
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setImage:myImage forState:UIControlStateNormal];
myButton.showsTouchWhenHighlighted = YES;
myButton.frame = CGRectMake(0.0, 3.0, 70,30);
[myButton addTarget:self action:@selector(BookmarkButtonPressed) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *rightbutton = [[UIBarButtonItem alloc] initWithCustomView:myButton];
self.navigationItem.rightBarButtonItem = rightbutton;

将此方法放在viewDidLoad

-(void)BookmarkButtonPressed

{

      //Do ur work here for Button Action

}