ios change UIButton image at runtime more than one time - cocoa-touch

I am using storyboard and i want to do a 3 stars priority button, at the first view the stars will appear off (not shining and that is means priority =0), when you first press this button the image of the three not shining stars with change to one star shining, when you press this button again (which is the button with the 3 stars image background) one star will be shining and that means priority = 1 (the image changes), and the press # 2 two stars will be shining, and pressing again make the three stars shining, and in the next press it starts from beginning (none of the stars is shining).
I used this code to implement the button but i do not know how to change the image. any help ?
UIButton *btnTwo = [UIButton buttonWithType:UIButtonTypeRoundedRect];
UIImage *btnImage = [UIImage imageNamed:#"3star.png"];
[btnTwo setImage:btnImage forState:UIControlStateNormal];
btnTwo.frame = CGRectMake(40, 140, 240, 30);
[self.view addSubview:btnTwo];

Create a method which will be called when the button is pressed:
[btnTwo addTarget:self action:#selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
and if you don't want to make a property declaration for the button add a tag identifier
btnTwo.tag = 3; //for ex.
in the method you created
-(void) buttonPressed{
UIButton *button = (UIButton*)[self.view viewWithTag:3];
[button setImage:[UIImage imageNamed:#"newImage.png"] forState:UIControlStateNormal];
}
In this method you could then provide logic to assign the correct image based on the number of times pressed.

Related

Custom UIButton background image not appearing until tapped

In app my, if you tap on a certain area a UIPopoverController appears with UIButtons that perform certain tasks when clicked. The UIButtons (called CableDisconnectButton) are a subclassed UIButton so I could add two additional properties to them. I also add UILabels to go over the buttons
However, the background images of the buttons are invisible or don't appear until I tap on the screen somewhere. The UIlabels show up fine, but not the buttons. It can be a tap on the UIPopoverController or anywhere else on the screen. Once I've tapped that first time, the buttons will be there until the app is closed. So, this only happens right after launch and up until I first open that UIPopover. I tap plenty of times before opening the popover.
The functionality of the buttons and everything else works fine, but the background images are hidden on that first launch and I have no idea why.
Here's how I create the buttons and UILabel:
//create custom button
CableDisconnectButton *removeConnectionButton = [CableDisconnectButton buttonWithType:UIButtonTypeCustom];
removeConnectionButton.frame = CGRectMake(x, y, 190, 80);
removeConnectionButton.backgroundColor = [UIColor clearColor];
[removeConnectionButton setBackgroundImage:[UIImage imageNamed:#"images/cable_disconnect_button.png"] forState:UIControlStateNormal];
[removeConnectionButton setBackgroundImage:[UIImage imageNamed:#"images/cable_disconnect_button_over.png"] forState:UIControlStateHighlighted];
//set input and output jacks to button properties
removeConnectionButton.inputJack = inputJack;
removeConnectionButton.outputJack = self.outputJackView;
//add action to button
[removeConnectionButton addTarget:self action:#selector(removeConnectionButtonTarget:) forControlEvents:UIControlEventTouchUpInside];
//create label for output
UILabel *outputConnectionLabel = [[UILabel alloc] initWithFrame:CGRectMake(x+18, y+5, 180, 22)];
outputConnectionLabel.backgroundColor = [UIColor clearColor];
outputConnectionLabel.textColor = [UIColor whiteColor];
outputConnectionLabel.text = self.outputJackView.jackDisplayName;
outputConnectionLabel.font = [UIFont systemFontOfSize:16];
//add subviews
[self addSubview:removeConnectionButton];
[self addSubview:outputConnectionLabel];
I've tried to add a regular, non-custom UIButton and it appears without the tap. I suspect it may have something to do with the subclassed UIButton, but I'm not sure why. The extra properties added to the UIButton are strings that are crucial to the functionality of the and can't be omitted.
After beating my head off the desk for days, I ran into the "Clean Build Folder" option. I've cleaned the project plenty of times, but wasn't aware of "Clean Build Folder". To execute this, simple hold the Option key, click Product from the menu and select Clean Build Folder.
So, if your app isn't behaving the way it should and it makes no sense AT ALL, try this.

Buttons won't hide after returning from another View Controller

I have an app with a tab bar and a number of tab bar items, each with its own VC. On the HOME tab bar view I have a set of UIButtons programmatically generated. I have one specific button ("Hide Buttons") that, when pressed, disables/hides the others. Works as expected.
However, when I tap a second tab bar item and then return to the original and tap the "Hide Buttons" button - they stay visible/enabled. If I set a breakpoint in the method called by the "Hide Buttons" button, I noted the memory address of one of the buttons and after tabbing to another view and returning, I notice the same UIButton memory address is different. Not sure why.
The UIButtons are all defined in the HOME VC inside the #implementation block in the form UIButton *originalButton; UIButton *hideButtonsButton; etc and initialized in viewDidAppear: using the following type of code:
// ORIGINAL BUTTON TAG = 1
originalButton = [UIButton buttonWithType:UIButtonTypeCustom];
[originalButton addTarget:self action:#selector(originalButtonWasPressed:) forControlEvents:UIControlEventTouchUpInside];
originalButton.frame = CGRectMake(20.0, 30.0, 100.0, 39.0);
UIImage *originalButtonImage = [[UIImage imageNamed:#"originalreg.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(18, 18, 18, 18)];
UIImage *originalButtonImageHighlight = [[UIImage imageNamed:#"originalregblue.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(18, 18, 18, 18)];
[originalButton setBackgroundImage:originalButtonImage forState:UIControlStateNormal];
[originalButton setBackgroundImage:originalButtonImageHighlight forState:UIControlStateHighlighted];
[self.view addSubview:originalButton];
Any guidance appreciated!
Duh. I moved the call to the button initialization method to viewDidLoad vs. viewDidAppear. All is fine now.

Choosing a button with a variable

I have this working in C#, but don't know where to go with Objective C (Xcode specifically).
I have 8 buttons
Stack1, Stack2, etc.
I want to choose Stack(variable) and change the image.
In C# I used
Button Stacks = this.Controls["Stack" + StackNumber.ToString()] as Button;
Stacks.BackgroundImage = .....
Can I do this in Objective C also?
I hope I understand your question correctly. You want to change button's image by clicking on another button. You can assign tag property to your different buttons like stack1.tag = 1001; , stack2.tag = 1002; , stack3.tag = 1003;
Now in your button click method :
- (IBAction)buttonStack1Click:(id)sender // for stack1 button
{
UIButton *tempStack = (UIButton *)[self.view viewWithTag:1003]; //to change image of stack3 button
// Now change the image of stack3 button
[tempStack setImage:[UIImage imageNamed:#"su.png"] forState:UIControlStateNormal];
}
Hope it gives an idea...
Take help of for loop and implement the code below :
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];
Any query arises,you can tell me.. hope that helps you.
If you want to perform certain function when a button is clicked then there are two ways..
One is Sarah way:Creating Button programmatically
The Other ways is if you are designing buttons in your interface builder :
Then :
1) Make those Buttons an IBOutlet..Also Make IBAction(Lots of tutorials available online..google them)
2) The IBAction will be something like this : - (IBAction)StackButton(YourNumber)Clicked:(id)sender {
In that function change the image of the button you want.
Like
[StackButton1 setImage:MyImage forState: UIControlStateNormal];

Change Round Rect Button background color on StateHighlighted

I'm trying to change the background color of a button when it's selected and don't want to use an image.
[mBtn setBackgroundColor:[UIColor grayColor] forState:UIControlStateHighlighted];
Any thoughts?
I'm replying to this old thread because it pops up consistently in searches for a solution to this problem and I have seen no solution elsewhere. It is truly annoying that setTintColor only applies to the highlighted state of a UIButton. Six months ago, it was equally annoying that it applied only to iOS 5, but that will hopefully be less of an issue going forward. With that in mind, I've drawn upon and combined a number of community suggestions to composite a general purpose solution to tinting a group of buttons in their normal state.
The method below accepts an NSArray of UIButtons and a set of color specifications as input. It applies the color specifications to one button using setTintColor, renders the result to a UIImage, and applies that image as the background image of the entire set of buttons. This avoids the need to create discrete image files for button colors. Also, it does so using a stretchable image so that it may work with a collection of buttons of different sizes (though note that it assumes the default corner rounding factors of UIButton). I hope you'll find it useful for iOS 5 targets.
- (void) setColorOfButtons:(NSArray*)buttons red:(float)red green:(float)green blue:(float)blue alpha:(float)alpha {
if (buttons.count == 0) {
return;
}
// get the first button
NSEnumerator* buttonEnum = [buttons objectEnumerator];
UIButton* button = (UIButton*)[buttonEnum nextObject];
// set the button's highlight color
[button setTintColor:[UIColor colorWithRed:red/255.9999f green:green/255.9999f blue:blue/255.9999f alpha:alpha]];
// clear any existing background image
[button setBackgroundImage:nil forState:UIControlStateNormal];
// place the button into highlighted state with no title
BOOL wasHighlighted = button.highlighted;
NSString* savedTitle = [button titleForState:UIControlStateNormal];
[button setTitle:nil forState:UIControlStateNormal];
[button setHighlighted:YES];
// render the highlighted state of the button into an image
UIGraphicsBeginImageContext(button.layer.frame.size);
CGContextRef graphicsContext = UIGraphicsGetCurrentContext();
[button.layer renderInContext:graphicsContext];
UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
UIImage* stretchableImage = [image stretchableImageWithLeftCapWidth:12 topCapHeight:0];
UIGraphicsEndImageContext();
// restore the button's state and title
[button setHighlighted:wasHighlighted];
[button setTitle:savedTitle forState:UIControlStateNormal];
// set background image of all buttons
do {
[button setBackgroundImage:stretchableImage forState:UIControlStateNormal];
} while (button = (UIButton*)[buttonEnum nextObject]);
}
[mBtn setTintColor:[UIColor grayColor]];
This only effects the highlighted state, so I believe that this is what you're looking for.
You can also set it from Interface Builder, from the Highlight Tint drop-down menu.
Just for people that will land here like I did when searching for changing background colors for highlighted state...
I ended up with an UIButton subclass that has a property for backgroundHighlightColor and tracks highlighting through KVO. Here's the link to GitHub: SOHighlightButton
You should be able to adapt it to any other scenario if you need more / other properties ot the UIButton to change if highlighted.
There is no method like this, setBackgroundColor: forState:
Check documentation. you need to use image.

How to change UIButton's background image while clicking it?

I have a UIButton in each of my tableview's cells. I want to glow the uibutton while click action happends. I set an image as its background image using the code
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(270,10,30,30);
[button setImage:[UIImage imageNamed:#"image.png"] forState:UIControlStateNormal];
[button addTarget:self action:#selector(action:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor clearColor];
The image.png is little bit darker image. Because i want to show a click effect by showing a glowed image.
Now shall i glow the image.png by code while clicking happends? Or should i create a new glowing image(say image_glow.png) with the same dimension and replace the previous one?
Whatever, please explain how to implement this....
The best way is to use multiple images.
You can set different image to different state of a UIButton by using setImage method.
As i see, you have set image only for UIControlStateNormal state, which makes all other states of a button to use the same image.
reference : UIButton States
Hope this helps.