iphone UIBarButtonItem initWithImage - 点击时不突出显示

时间:2010-08-31 18:55:11

标签: iphone highlighting uibarbuttonitem

我可以创建一个这样的按钮,动作效果很好:

UIBarButtonItem *myBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"image.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(myMethod:)];

但是,点击屏幕上的按钮时,不会显示“向下状态突出显示”。我已经尝试了一切。您是否可以使用自定义图像在UIBarButtonItem上获得突出显示?

2 个答案:

答案 0 :(得分:3)

尝试这样的事情(setShowsTouchWhenHighlighted:就是你要找的东西):

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];

答案 1 :(得分:0)

对于大多数初学者来说,也许有点容易:

按钮创建代码

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

行动处理程序代码

- (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;
    }
}

说明

非常直接。我以编程方式创建按钮并将其添加到视图导航栏。当然,这仅在使用NavigationController时才有效。

当用户点击按钮开始编辑相关表格视图时,该功能会检查表格编辑状态并更改按钮文本和样式。