UIBarButtonItem : selected / unselected an item

怎甘沉沦 提交于 2019-12-12 09:26:47

问题


I have a favorite image to display on a UIBarButtonItem, on an toolbar.

How do you do to change it when this item is unselected/selected? like this screenshot:

Thanks!


回答1:


You can make two arrays with UIBarButtonItems: one with the first image and one with the second image. Like this:

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

and then switch between the two sets of toolbar items with:

toolbar.items = self.itemsWithSelected; // or self.itemsWithUnselected

If you have more than just the one button on your toolbar then just add the rest of the items to both arrays.




回答2:


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


来源:https://stackoverflow.com/questions/2261910/uibarbuttonitem-selected-unselected-an-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!