我有一个最喜欢的图片显示在工具栏上的UIBarButtonItem
上。
取消选择/选择此项目时,如何更改?喜欢这个截图:
谢谢!
答案 0 :(得分:3)
您可以使用UIBarButtonItems创建两个数组:一个包含第一个图像,另一个包含第二个图像。像这样:
// array with unselected
UIBarButtonItem *unselectedItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_unselected.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(doStuff:)];
self.itemsWithUnselected = [NSArray arrayWithObject:unselectedItem]; // declared as NSArray*
[unselectedItem release];
// array with selected
UIBarButtonItem *selectedItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_selected.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(doStuff:)];
self.itemsWithSelected = [NSArray arrayWithObject:selectedItem]; // declared as NSArray*
[selectedItem release];
然后在两组工具栏项之间切换:
toolbar.items = self.itemsWithSelected; // or self.itemsWithUnselected
如果工具栏上只有一个按钮,那么只需将其余项添加到两个数组中。
答案 1 :(得分:-1)
// First create UIButton object
UIButton *btnCustom = [UIButton buttonWithType:UIButtonTypeCustom];
// Set Frame because without frame your button can not be shown on navigation bar
[btnCustom setFrame:CGRectMake(0.0, 0.0, 20.0, 20.0)];
// Set unselected image
[btnCustom setImage:[UIImage imageNamed:@"YOUR_IMAGE_NAME_UNSELECTED"] forState:UIControlStateNormal];
// set selected image
[btnCustom setImage:[UIImage imageNamed:@"YOUR_IMAGE_NAME_SELECTED"] forState:UIControlStateSelected];
// set action method
[btnCustom addTarget:self action:@selector(btnCustom_click:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *btnCustomBar = [[UIBarButtonItem alloc]initWithCustomView:btnCustom];
[self.navigationItem setRightBarButtonItem:btnCustomBar];
// action Method
- (IBAction)btnCustom_click:(id)sender
{
if(![sender isSelected])
[sender setSelected:YES];
else
[sender setSelected:NO];
}