开发者

iphone UIBarButtonItem initWithImage - doesn't highlight when tapped

I can create a button like this, and the action works fine:

UIBarButtonItem *myBtn = [[UIBa开发者_如何学运维rButtonItem alloc] initWithImage:[UIImage imageNamed:@"image.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(myMethod:)];

However, when tapping the button on screen, no Down state highlight is displayed. I've tried everything. Can you not get a highlight on a UIBarButtonItem with a custom image?


Try something like this (setShowsTouchWhenHighlighted: is what you're looking for):

UIImage* image = [UIImage imageNamed:@"image.png"];
CGRect frame = CGRectMake(0, 0, image.size.width, image.size.height);
UIButton* button = [[UIButton alloc] initWithFrame:frame];
[button setBackgroundImage:image forState:UIControlStateNormal];
[button addTarget:self action:@selector(myMethod:) forControlEvents:UIControlEventTouchUpInside];
[button setShowsTouchWhenHighlighted:YES];
UIBarButtonItem* barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
[self.navigationItem setRightBarButtonItem:barButtonItem];
[barButtonItem release];
[button release];


Maybe something a little bit easier for most beginners:

Code for Button Creation

UIBarButtonItem *editButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(editCells:)]; 
self.navigationItem.rightBarButtonItem = editButtonItem;
[editButtonItem release];

Code for Action Handler

- (void)editCells:(id)sender {
    UIBarButtonItem *buttonItem = (UIBarButtonItem *)sender;

    if (self.tableView.editing == YES) {
        self.tableView.editing = NO;
        buttonItem.title = @"Edit";
        buttonItem.style = UIBarButtonItemStyleBordered;        
    }
    else {
        self.tableView.editing = YES;
        buttonItem.title = @"Done";
        buttonItem.style = UIBarButtonItemStyleDone;
    }
}

Explanation

Pretty straight forward. I create the button programatically and add it to the views navigation bar. Of course, this only works when using a NavigationController.

When the user clicks the button to start editing the related table view, the function checks the table editing state and changes the text of the button as well as the style.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜