How to change button's Image on clicking it in ios - ios

Confession: I have been through every possible link I could find, but unfortunately none work for me.
I am creating buttons dynamically. When a button is selected, it should change the color of the selected button and the rest should remain the default color. This way, the user can identify which button is selected.
Suppose there are 3 buttons: all blue in color, and when I select the first one, it should change to white and other two should remain blue. When I select the second, the first one should go back to blue and the second should now be white.
btnCounts data I am fetching from server and would vary.
-(void)createButtons{
for (int i=0; i<btnCounts; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setTag:i];
[btn setFrame:CGRectMake(xVal, 0, width/btnCounts, 40)];
// [btn setImage:[UIImage imageNamed:#"btn_image.png"] forState:UIControlStateNormal];
[btn setBackgroundImage:[UIImage imageNamed:#"blue.png"] forState:UIControlStateNormal];
[btn setBackgroundImage:[UIImage imageNamed:#"white.png"] forState:UIControlStateSelected];
[btn setTitle:name forState:UIControlStateNormal];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[scrV addSubview:btn];
xVal += self.view.frame.size.width/btnCounts+1;
}
}
Now, in btnClicked: method I am passing the button as a parameter, so that I can use selected button.
-(void)btnClicked:(UIButton *)button
{
int tag = (int)button.tag;
//...
}
Please help me to find what I am missing here.
Thanks.

Create an instance UIButton variable to house the selected button so that you can deselect it when the next button is tapped. If you only pass the currently-tapped button to your btnClicked: method, you won't know which button to deselect (if any).
#implementation ClassName {
UIButton *previousButton;
}
...
- (void)btnClicked:(UIButton *)button
{
if(previousButton)
[previousButton setBackgroundColor:[UIColor blueColor]];
previousButton = button;
[button setBackgroundColor:[UIColor whiteColor]];
// do whatever else you need to do here
}

For that you need to store selected button in temporary object.
Create button in interface(.h) file:
UIButton *selectedButton;
Than add following line in -(void)createButtons method before for loop.
selectedButton = nil;
for() {...}
Here selectedButton is set to nil because initially none of the buttons are selected.
And finally replace your -(void)btnClicked:(UIButton *)button method with following method.
-(void)btnClicked:(UIButton *)button {
if(selectedButton) {
selectedButton.selected = NO;
}
button.selected = YES;
selectedButton = button;
}
If you want to make any button initially selected than assign that button to selectedButton like in btnClicked method.

Related

can't change image of uibutton after pressing other buttons

i have 2 buttons that keep with the pressed image even when they are released, until the other button is pressed, then the image returns to the normal image my code is this:
- (IBAction)button1_touch:(UIButton *)sender
{
[Button2 setImage:[UIImage imageNamed:#"b2Released.png"] forState:UIControlStateNormal];
[Button1 setImage:[UIImage imageNamed:#"b1Pressed.png"] forState:UIControlStateNormal];
}
- (IBAction)button2_touch:(UIButton *)sender
{
[Button1 setImage:[UIImage imageNamed:#"b1Released.png"] forState:UIControlStateNormal];
[Button2 setImage:[UIImage imageNamed:#"b2Pressed.png"] forState:UIControlStateNormal];
}
the code above works fine when the app starts, the behavior is the expected pressing both buttons, images change correctly, but when i press other button than those two, the "Button2" once it gets the "B2Pressed.png" image, it never returns to its released image, i wrote a nslog in button1_touch and it gets printed as expected, and the Button1 gets its pressed image, but the Button2 is not getting its released image, is like the method setImage of UiButton gets broken when i press other button than those two, other buttons are independent from those two, for me this behavior has absolutely no sense at all, could it be xcode broken? i am working on xcode 7.2
EDIT:
the problem occurs when i press another button only if that button has a action selector assigned to it (UIControlEventTouchUpInside).
You can use selected state of UIButton for this purpose:
- (void)viewDidLoad {
// ...
// the place where you do buttons setup
[button1 setImage:[UIImage imageNamed:#"b1Released"] forState:UIControlStateNormal];
[button1 setImage:[UIImage imageNamed:#"b1Pressed"] forState:UIControlStateSelected];
[button2 setImage:[UIImage imageNamed:#"b2Released"] forState:UIControlStateNormal];
[button2 setImage:[UIImage imageNamed:#"b2Pressed"] forState:UIControlStateSelected];
}
- (IBAction)firstButtonTouch:(UIButton *)sender {
button1.selected = YES;
button2.selected = NO;
}
- (IBAction)secondButtonTouch:(UIButton *)sender {
button1.selected = NO;
button2.selected = YES;
}

UIButton Selected State Image Freezes on Autorotation

I have a UIButton in the footer of UITableView. It has an empty checkbox as its unselected state, and a checked box as its selected state. It works perfectly in portrait, but if the view ever rotates to landscape, the button's image is frozen in whatever state it was when it rotated. The button still sends messages correctly after rotation, but the image does not change.
self.theButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.theButton setImage:checkbox
forState:UIControlStateNormal];
[self.theButton setImage:checkedBox
forState:UIControlStateSelected];
This code appears in the tableView:viewForFooterInSection: of my view controller. In the action linked to the button, I set self.theButton.selected = !self.theButton.selected;
What's going on?
You can do this in your button action
- (void)didTapCheckbox:(id)sender {
UIButton *btn =(UIButton *)sender;
if (btn.selected == YES) {
[btn setSelected:NO];
}
else{
[btn setSelected:YES];
}
}
instead of your code just do this
if(self.theButton == nil){
self.theButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.theButton setImage:checkbox
forState:UIControlStateNormal];
[self.theButton setImage:checkedBox
forState:UIControlStateSelected];
}

Change properties of programmatically created UIButton in a different IBAction

I have one method that creates a number of UIButton instances programmatically and positions them in the view. Another IBAction needs to change the background colour of one of these UIButton when fired however when I try to action it, it tells me that the Property not found on object of type UIView *
The button is created using:
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
[view addSubview:button];
When I try to access it from the other IBAction like:
button.backgroundColor = [UIColor blackColor];
It fails with the error noted above.
Any help is much appreciated. I saw another answer which suggested to create an array as an IBOutlet and access it that way but I'm wondering if there's another way.
Thanks!
declare this button in globally and identify each button in tag, just like or assume this
UIButton * button, *button2; // declare in your view controller.h
- (IBAction)butaction:(id)sender; //this is your color change method;
in your view controller.m wherever u add this button
button = [UIButton buttonWithType:UIButtonTypeCustom];
button.tag=10; //this is important
[self.view addSubview:button];
button1 = [UIButton buttonWithType:UIButtonTypeCustom];
button1.tag=20; //this is important
[self.view addSubview:button1];
//here ur color change method
- (IBAction) butaction:(UIButton*)sender {
switch (sender.tag)
{
case 10:
[button setBackgroundColor:[UIColor blackColor]];
break;
case 20:
[button1 setBackgroundColor:[UIColor blackColor]];
break;
default:
break;
}
}
Try this, it may be helpful
for (int index=1; index<=5; index++) {
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:#selector(ButtonClickedFunction:) forControlEvents:UIControlEventTouchUpInside];
button.tag= index;
[view addSubview:button];
};
implement this in IBAction
-(IBAction)ButtonClickedFunction:(UIButton *)button{
button.backgroundColor = [UIColor blackColor];
}
Note: In this I have created 5 buttons but not set frame. Please set frame according to your requirements.
Thanks

Is there anyway to add same scroll menubar at the navigation bar?

I have already posted my this problem another time but i have not got my answer perfectly.Here i am going to explain my problem another time, it is very important for me so at any cost i have to solve it.Now my problem is...
Suppose, I have 4 tabbaritem in a tabbarController and items "dashboard","order","product","customer".
every item of these tabbar is a calling there respective uiviewcontroller.
dashboar calling "DashboarViewController";
order calling "orderViewController";
product calling "ProductViewController";
customer calling "CustomerViewController";
Now, i have to set a scrolling menubar at every uiviewcontroller and this menu bar containing 4 buttons. These button names are same as tabbar items name "dashboard","order","product","customer".
Now when i press the button of the menu bar then respective controller will show same as for tabbar items. suppose i am pressing "order" tabbar item then it will show the "orderviewcontroller". when i will see this view controller it will also show me that menu bar at the top of the viewcontroller.Now, if i am click "product" button in this "orderviewcontroller" then it will sent back to me "productViewcontroller".
thats mean tabbar item and button of the scroll menubar will work same.
still now i have done these, my previous post image
How can i make same button in multiple view controller?
If some know how can do that then please explain it step by step.I do not need to give any code from you.just explain it step by step how can i do that after reading my previous post
Thanks In Advance.
Ha ha ha .....it was so much fun when i solved it.whatever i solved this problem in different way, i did not use scrollview button controller for controller just, in every controller i have made function to where buttons within a scrollview create and on action of button i have just change the selected index of the tabbar controller.
in -(void)viewDidload i wrote this code
UIView *scrollViewBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 45)];
scrollViewBackgroundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"topmenu_bg.png"]];
menuScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(5,0,320,40)];
menuScrollView.showsHorizontalScrollIndicator = FALSE;
menuScrollView.showsVerticalScrollIndicator = FALSE;
menuScrollView.bounces = TRUE;
[scrollViewBackgroundView addSubview:menuScrollView];
[self.view addSubview:scrollViewBackgroundView];
[self createMenuWithButtonSize:CGSizeMake(92.0, 30.0) withOffset:5.0f noOfButtons:7];
here is the button create and action
-(void)mybuttons:(id)sender{
NSLog(#"mybuttons called");
UIButton *button=(UIButton *)sender;
NSLog(#"button clicked is : %iBut \n\n",button.tag);
int m = button.tag;
for(int j=0;j<8;j++){
if(button.tag == m){
self.tabBarController.selectedIndex = m;
[button setBackgroundImage:[UIImage imageNamed:#"btn_topmenu_hover.png"] forState:UIControlStateHighlighted]; //sets the background Image]
}
if(button.tag != m){
[button setBackgroundImage:[UIImage imageNamed:#"btn_topmenu_normal.png"] forState:UIControlStateNormal]; //sets the background Image]
}
}
}
-(void)createMenuWithButtonSize:(CGSize)buttonSize withOffset:(CGFloat)offset noOfButtons:(int)totalNoOfButtons{
NSLog(#"inserting into the function for menu bar button creation");
for (int i = 0; i < totalNoOfButtons; i++) {
UIButton *button = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
[button addTarget:self action:#selector(mybuttons:) forControlEvents:UIControlEventTouchUpInside];
(button).titleLabel.font = [UIFont fontWithName:#"Arial" size:12];
if(i==0){
[button setTitle:[NSString stringWithFormat:#"Dashboard"] forState:UIControlStateNormal];//with title
[button setBackgroundImage:[UIImage imageNamed:#"btn_topmenu_hover.png"] forState:UIControlStateNormal]; //sets the background Image]
}
if(i==1){
[button setTitle:[NSString stringWithFormat:#"Order"] forState:UIControlStateNormal];//with title
[button setBackgroundImage:[UIImage imageNamed:#"btn_topmenu_normal.png"] forState:UIControlStateNormal]; //sets the background Image]
}
if(i==2){
[button setTitle:[NSString stringWithFormat:#"Product"] forState:UIControlStateNormal];//with title
[button setBackgroundImage:[UIImage imageNamed:#"btn_topmenu_normal.png"] forState:UIControlStateNormal]; //sets the background Image]
}
if(i==3){
[button setTitle:[NSString stringWithFormat:#"Customers"] forState:UIControlStateNormal];//with title
[button setBackgroundImage:[UIImage imageNamed:#"btn_topmenu_normal.png"] forState:UIControlStateNormal]; //sets the background Image]
}
if(i==4){
[button setTitle:[NSString stringWithFormat:#"Content"] forState:UIControlStateNormal];//with title
}
if(i==5){
[button setTitle:[NSString stringWithFormat:#"Site Analysis"] forState:UIControlStateNormal];//with title
[button setBackgroundImage:[UIImage imageNamed:#"btn_topmenu_normal.png"] forState:UIControlStateNormal]; //sets the background Image]
}
if(i==6){
[button setTitle:[NSString stringWithFormat:#"Store Settings"] forState:UIControlStateNormal];//with title
[button setBackgroundImage:[UIImage imageNamed:#"btn_topmenu_normal.png"] forState:UIControlStateNormal]; //sets the background Image]
}
if(i==7){
[button setTitle:[NSString stringWithFormat:#"CMS Settings"] forState:UIControlStateNormal];//with title
[button setBackgroundImage:[UIImage imageNamed:#"btn_topmenu_normal.png"] forState:UIControlStateNormal]; //sets the background Image]
}
button.frame = CGRectMake(i*(offset+buttonSize.width), 6.0, buttonSize.width, buttonSize.height);
button.clipsToBounds = YES;
button.showsTouchWhenHighlighted=YES;
button.layer.cornerRadius = 5;//half of the width
button.layer.borderColor=[UIColor clearColor].CGColor;
button.layer.borderWidth=0.0f;
button.tag=i;
[menuScrollView addSubview:button];
}
menuScrollView.contentSize=CGSizeMake((buttonSize.width + offset) * totalNoOfButtons, buttonSize.height);
[self.view addSubview:menuScrollView];
}

UIButton - On touch change image

When I touch the button at that time I want to change image & when i release the touch button image is as it is.
I want to apply below code but it's not with my expectation.
please give me any suggestion.....
-(IBAction)actionEnter:(id)sender{
if ([sender isSelected]) {
[sender setImage:[UIImage imageNamed:#"enter-hover.png"]
forState:UIControlStateNormal];
[sender setSelected:NO];
} else {
[sender setImage:[UIImage imageNamed:#"enter.png"]
forState:UIControlStateSelected];
[sender setSelected:YES];
}
You can use UIControlStateHighlighted for this.
[myButton setImage:[UIImage imageNamed:#"enter-hover.png"]
forState:UIControlStateHighlighted];
You can also set this from interface builder by setting the image for highlighted state.
I think this should do it. Set the images after creating the button
[yourButton setImage:[UIImage imageNamed:#"enter-hover.png"]
forState:UIControlStateSelected];
[yourButton setImage:[UIImage imageNamed:#"enter.png"]
forState:UIControlStateNormal];
and do this
- (IBAction)actionEnter:(id)sender{
UIButton *button = (UIButton *)sender;
button.selected = !button.selected;
}
In Swift:
button.setImage(UIImage(named: "enter.png"), forState: [.Selected, .Highlighted])
I think, you could set the image in the beginning for normal and selected state ..
Try with below when you create the UIButton object. [Use the images as per your requirement]
[myButton setImage:[UIImage imageNamed:#"enter.png"]
forState:UIControlStateNormal];
[myButton setImage:[UIImage imageNamed:#"enter-hover.png"]
forState:UIControlStateSelected];
#7KV7 got me thinking. I have favorite and ignore buttons that I want to use to mark favorite pictures and pictures that I never want to see again. I used his method to initialize the buttons and then slightly modified his method to toggle the buttons on and off.
In this example, if you mark a picture as a favorite, you want to turn off the ignore button and vice versa. The delegate handles the database stuff.
self.favoriteButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.ignoreButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.favoriteButton setImage:[UIImage imageNamed:#"Favorite-Selected"]
forState:UIControlStateSelected];
[self.favoriteButton setImage:[UIImage imageNamed:#"Favorite"]
forState:UIControlStateNormal];
[self.ignoreButton setImage:[UIImage imageNamed:#"Ignore-Selected"]
forState:UIControlStateSelected];
[self.ignoreButton setImage:[UIImage imageNamed:#"Ignore"]
forState:UIControlStateNormal];
If you are just toggling a button on or off, you won’t need to make it a property, since the buttonPressed sender knows which button has been pressed. I need to have them be property since I need to tell the opposite button to turn its highlight off.
- (void)favoriteIgnore:(UIButton *)buttonPressed {
// Toggle the tapped button
buttonPressed.selected = ( buttonPressed.selected) ? NO : YES;
id <ScoringToolbarDelegate> TB_delegate = _delegate;
// Turn off the other button and call the delegate
if ([buttonPressed.currentTitle isEqualToString:#"favorite"]) {
self.ignoreButton.selected = NO;
[TB_delegate favoriteButtonPressed];
} else {
self.favoriteButton.selected = NO;
[TB_delegate ignoreButtonPressed];
}
}
to change the image immediately use the backgroundImage property.

Resources