I have a custom ImagePicker. A UIScrollView with images from my NSDocumentDirectory then I added the button as my images' frame, Like a thumbnail View. What I added is when It is selected then dismissed, the next time the view loads/appears/shows it will have an image checkmark already. It was okay. But what I need is, when I tap an image it will be selected already or the image "checkmark" will be shown, then when I tap the same image the checkmark will be gone.
Here is an explanation of the codes I have:
// The UISCrollView
- (void)viewDidLoad {
// Create view
UIScrollView *view = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,1024.0f,768.0f)];
int row = 0;
int column = 0;
for(int i = 0; i < _thumbs.count; ++i) {
UIImage *thumb = [_thumbs objectAtIndex:i];
myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame = CGRectMake(column*140+24, row*150+10, 100, 100);
[myButton setImage:thumb forState:UIControlStateNormal];
[myButton addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
myButton.tag = i;
NSLog(#"%i",i);
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSInteger selectedImageSlot1 = [prefs integerForKey:#"selected1"];
if ( selectedImageSlot1 == i){
[self turnButtonToSelected];
}
}
// When button is tapped
- (IBAction)buttonClicked:(id)sender {
myButton = (UIButton *)sender;
self.selectedImage = [_images objectAtIndex:myButton.tag];
[[NSUserDefaults standardUserDefaults] setInteger:myButton.tag forKey:#"selected1"];
[self dismissModalViewControllerAnimated:NO];
}
// method when button is selected
- (void)turnButtonToSelected
{
UIImage *bgImage = [UIImage imageNamed:#"Checkmark.png"];
[myButton setBackgroundImage:bgImage forState:UIControlStateNormal];
[myButton setBackgroundImage:bgImage forState:UIControlStateHighlighted];
[myButton setBackgroundImage:bgImage forState:UIControlStateDisabled];
[myButton setEnabled:NO];
}
First u need to keep the selected image index around, so create a selectedImageIndex instance variable.
Then in viewDidLoad there is no need to call
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSInteger selectedImageSlot1 = [prefs integerForKey:#"selected1"];
in the for loop...
Put it before the for loop and store the selected image index in selectedImageIndex.
- (void)viewDidLoad {
// Create view
UIScrollView *view = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,1024.0f,768.0f)];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
self.selectedImageIndex = [prefs integerForKey:#"selected1"];
int row = 0;
int column = 0;
for(int i = 0; i < _thumbs.count+1; ++i) {
UIImage *thumb = [_thumbs objectAtIndex:i];
myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame = CGRectMake(column*140+24, row*150+10, 100, 100);
[myButton setImage:thumb forState:UIControlStateNormal];
[myButton addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
myButton.tag = i+1;
NSLog(#"%i",i);
if (self.selectedImageIndex == myButton.tag){
[self turnButtonToSelected:myButton];
}
}
Remove the line [myButton setEnabled:NO]; from turnButtonToSelected so that the user can re-tap on the button to deselect it. change turnButtonToSelected to:
- (void)turnButtonToSelected:(UIButton *)button
{
UIImage *bgImage = [UIImage imageNamed:#"Checkmark.png"];
[button setBackgroundImage:bgImage forState:UIControlStateNormal];
[button setBackgroundImage:bgImage forState:UIControlStateHighlighted];
[button setBackgroundImage:bgImage forState:UIControlStateDisabled];
}
- (void)turnButtonToDeselected:(UIButton *)button
{
UIImage *bgImage = [UIImage imageNamed:#"Not-Checkmark.png"];
[button setBackgroundImage:bgImage forState:UIControlStateNormal];
[button setBackgroundImage:bgImage forState:UIControlStateHighlighted];
[button setBackgroundImage:bgImage forState:UIControlStateDisabled];
}
Then when user tap on an image, u check if this image is currently selected.
If yes - u call turnButtonToDeselected.
If no - u call turnButtonToSelected
- (IBAction)buttonClicked:(id)sender {
myButton = (UIButton *)sender;
self.selectedImage = [_images objectAtIndex:myButton.tag - 1];
[[NSUserDefaults standardUserDefaults] setInteger:myButton.tag forKey:#"selected1"];
if (myButton.tag == self.selectedImageIndex) {
// user tap on a button that was selected, so we need to deselect it
[self turnButtonToDeselected:myButton];
}
else {
// user tap on a button that wasn't selected
// first we check if there is a selected button, if yes we need to deselect it
if (self.selectedImageIndex > 0) {
// get the selected button
UIButton *selectedButton = (UIButton *)[self.view viewWithTag:self.selectedImageIndex];
// deselect it
[self turnButtonToDeselected:selectedButton];
}
// now we can select the button the user tapped on
[self turnButtonToSelected:myButton];
// save the selected index
self.selectedImageIndex = myButton.tag;
}
}
One more thing, in viewDidLoad set the button tag to i+1
Keep a Boolean value for if the button is selected or not. In your interface keep a boolean variable named BOOL selected; Keep track of the value, and manage to save it. Then in your turnButtonToSelected method add this:
- (void)turnButtonToSelected
{
selected = !selected;
if (selected)
{
UIImage *bgImage = [UIImage imageNamed:#"Checkmark.png"];
[myButton setBackgroundImage:bgImage forState:UIControlStateNormal];
[myButton setBackgroundImage:bgImage forState:UIControlStateHighlighted];
[myButton setBackgroundImage:bgImage forState:UIControlStateDisabled];
}
else
{
// set button image without the check mark
}
}
This will make sure, if the button was selected previously and now tapped again the checkmark
will be gone.
you need to create button array.And when button click event you need to check button have set checkmark image or not.
-(IBAction)buttonclickevent:(id)sender{
UIButton *btn=sender;
UIButton *currentbutton=[ButtonArray objectAtIndex:btn.tag];
if([currentbutton.currentImage isEqual:[UIImage imageNamed:#"Checkmark.png"]])
[currentbutton setImage:[UIImage imageNamed:#"normal.png"]forState:UIControlStateNormal];
}
else {
[currentbutton setImage:[UIImage imageNamed:#"Checkmark.png"]forState:UIControlStateNormal];
}
}
Related
Im really having a problem with my image with button frame,
What I want is:
1. When it is selected it will have a checkmark
2. When the view is dismissed then returned back to the previous screen it will still have the check in the image selected
3. When I tap the selected image or another image it will remove the checkmark.
I was able to do it but I'm having problem with the setting of image:
What I want is this:
UIImage *bgImage = [UIImage imageNamed:#"AGIPC-Checkmark-iPhone.png"];
[myButton setBackgroundImage:bgImage forState:UIControlStateDisabled];
[myButton setEnabled:NO];
But this is the function I needed:
UIImage *bgImage = [UIImage imageNamed:#"AGIPC-Checkmark-iPhone.png"];
[myButton setImage:bgImage forState:UIControlStateSelected];
[myButton setSelected:YES];
Here is the code below(If there is something wrong with what I'm doing please tell me, Thanks):
- (void)viewDidLoad {
UIImage *bgImage = [UIImage imageNamed:#"AGIPC-Checkmark-iPhone.png"];
[myButton setBackgroundImage:bgImage forState:UIControlStateHighlighted];
[myButton setBackgroundImage:bgImage forState:UIControlStateDisabled];
// Create view
UIScrollView *view = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,1024.0f,768.0f)];
int row = 0;
int column = 0;
for(int i = 0; i < _thumbs.count; ++i) {
UIImage *thumb = [_thumbs objectAtIndex:i];
myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame = CGRectMake(column*140+24, row*150+10, 100, 100);
[myButton setImage:thumb forState:UIControlStateNormal];
[myButton addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
myButton.tag = i;
NSLog(#"%i",i);
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSInteger selectedImageSlot1 = [prefs integerForKey:#"selected1"];
if ( selectedImageSlot1 == i){
[self turnButtonToSelected];
}
[view addSubview:myButton];
if (column == 6) {
column = 0;
row++;
} else {
column++;
}
}
[view setContentSize:CGSizeMake(1024, (row+1) * 150 + 10)];
}
- (void)turnButtonToSelected
{ UIImage *bgImage = [UIImage imageNamed:#"AGIPC-Checkmark-iPhone.png"];
[myButton setBackgroundImage:bgImage forState:UIControlStateNormal];
[myButton setBackgroundImage:bgImage forState:UIControlStateHighlighted];
[myButton setBackgroundImage:bgImage forState:UIControlStateDisabled];
[myButton setEnabled:NO];
}
- (void)highlightButton:(UIButton *)a {
//[self turnButtonToSelected];
}
- (IBAction)buttonClicked:(id)sender {
myButton = (UIButton *)sender;
self.selectedImage = [_images objectAtIndex:myButton.tag];
if (myButton.selected) {
[sender setSelected:NO];
}else {
UIImage *bgImage = [UIImage imageNamed:#"AGIPC-Checkmark-iPhone.png"];
[sender setImage:bgImage forState:UIControlStateSelected];
[sender setSelected:YES];
}
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setInteger:myButton.tag forKey:#"slot1"];
[[NSUserDefaults standardUserDefaults] setInteger:myButton.tag forKey:#"selected1"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self performSelector:#selector(highlightButton:) withObject:sender afterDelay:0.0];
[self dismissModalViewControllerAnimated:NO];
}
Or is there a way to forcefully make a button enabled whenever it is disabled when tapped also?
I have just tried this on a different approach.
For me it works just fine and achieves your effect.
Let me know if you need further explanation or the entire Xcode project.
- (void)viewDidLoad
{
[super viewDidLoad];
//button 1
UIButton *imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
imageButton.frame = CGRectMake(30, 50, 100, 80);
UIImage *btnImage = [UIImage imageNamed:#"DSC_5359.JPG"];
[imageButton setBackgroundImage:btnImage forState:UIControlStateNormal];
[imageButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchDown];
//button 2
UIButton *imageButton2 = [UIButton buttonWithType:UIButtonTypeCustom];
imageButton2.frame = CGRectMake(180, 50, 100, 80);
UIImage *btnImage2 = [UIImage imageNamed:#"DSC_5355.JPG"];
[imageButton2 setBackgroundImage:btnImage2 forState:UIControlStateNormal];
[imageButton2 addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:imageButton];
[self.view addSubview:imageButton2];
}
- (void)buttonClicked:(UIButton*)button
{
//NSLog(#"Button clicked! %#", button);
UIImage *checkmarkImage = [UIImage imageNamed:#"check.png"];
UIImage *empty = nil;
//NSLog(#"Imageview: %d", button.imageView.tag);
if (button.imageView.tag == 0)
{
[button setImage:checkmarkImage forState:UIControlStateNormal];
button.imageView.tag = 1;
}
else
{
[button setImage:empty forState:UIControlStateNormal];
button.imageView.tag = 0;
}
}
Best, Chris
Update: I have updated the code. Here is the entire ViewController. Note: I would solve this using coreData to store the current index. The following code is not the best to solve this issue but is based on your initial code!
//
// SOViewController.m
// SOImageOverlay
//
// Created by Chris on 24.07.12.
//
#import "SOViewController.h"
#interface SOViewController ()
#end
#define CHECKMARK_IMAGE #"check.png"
#implementation SOViewController
#synthesize buttons = _buttons;
#pragma mark - Custom getter
- (NSMutableArray*)buttons
{
if (_buttons == nil)
_buttons = [[NSMutableArray alloc] init];
return _buttons;
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// UIImage *bgImage = [UIImage imageNamed:CHECKMARK_IMAGE];
// UIButton *myButton =
// [myButton setBackgroundImage:bgImage forState:UIControlStateHighlighted];
// [myButton setBackgroundImage:bgImage forState:UIControlStateDisabled];
// Create view
// UIScrollView *view = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,1024.0f,768.0f)];
int row = 0;
int column = 0;
for(int i = 0; i < 2; ++i) {
/*UIImage *thumb = [_thumbs objectAtIndex:i];
myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame = CGRectMake(column*140+24, row*150+10, 100, 100);
[myButton setImage:thumb forState:UIControlStateNormal];
[myButton addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
myButton.tag = i;
NSLog(#"%i",i);*/
UIButton *imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
if (i == 0)
{
UIImage *btnImage = [UIImage imageNamed:#"DSC_5359.JPG"];
imageButton.frame = CGRectMake(30, 50, 100, 80);
[imageButton setBackgroundImage:btnImage forState:UIControlStateNormal];
}
else if (i == 1)
{
UIImage *btnImage = [UIImage imageNamed:#"DSC_5355.JPG"];
imageButton.frame = CGRectMake(180, 50, 100, 80);
[imageButton setBackgroundImage:btnImage forState:UIControlStateNormal];
}
[imageButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchDown];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSInteger selectedImageSlot1 = [prefs integerForKey:#"selected1"];
if ( selectedImageSlot1 == i){
[self turnButtonToSelected:imageButton];
}
[self.view addSubview:imageButton];
//adding current button into buttons array
[self.buttons addObject:imageButton];
if (column == 6) {
column = 0;
row++;
} else {
column++;
}
}
//[view setContentSize:CGSizeMake(1024, (row+1) * 150 + 10)];
// //button 1
// UIButton *imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
// imageButton.frame = CGRectMake(30, 50, 100, 80);
// UIImage *btnImage = [UIImage imageNamed:#"DSC_5359.JPG"];
// [imageButton setBackgroundImage:btnImage forState:UIControlStateNormal];
// [imageButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchDown];
//
// //button 2
// UIButton *imageButton2 = [UIButton buttonWithType:UIButtonTypeCustom];
// imageButton2.frame = CGRectMake(180, 50, 100, 80);
// UIImage *btnImage2 = [UIImage imageNamed:#"DSC_5355.JPG"];
// [imageButton2 setBackgroundImage:btnImage2 forState:UIControlStateNormal];
// [imageButton2 addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchDown];
//
// [self.view addSubview:imageButton];
// [self.view addSubview:imageButton2];
}
//- (void)buttonClicked:(UIButton*)button
//{
// //NSLog(#"Button clicked! %#", button);
//
// UIImage *checkmarkImage = [UIImage imageNamed:#"check.png"];
// UIImage *empty = nil;
//
// //NSLog(#"Imageview: %d", button.imageView.tag);
// if (button.imageView.tag == 0)
// {
// [button setImage:checkmarkImage forState:UIControlStateNormal];
// button.imageView.tag = 1;
// }
// else
// {
// [button setImage:empty forState:UIControlStateNormal];
// button.imageView.tag = 0;
// }
//}
// code from stackoverflow
// ------------------------------------------------------------
- (void)turnButtonToSelected:(UIButton*)button
{
UIImage *bgImage = [UIImage imageNamed:CHECKMARK_IMAGE];
//UIButton *myButton = button; //just to use the copied code
button.selected = YES;
[button setImage:bgImage forState:UIControlStateSelected];
// [myButton setBackgroundImage:bgImage forState:UIControlStateNormal];
// [myButton setBackgroundImage:bgImage forState:UIControlStateHighlighted];
// [myButton setBackgroundImage:bgImage forState:UIControlStateDisabled];
// [myButton setEnabled:NO];
}
- (void)highlightButton:(UIButton *)a {
//[self turnButtonToSelected];
}
- (IBAction)buttonClicked:(id)sender
{
UIButton *myButton = (UIButton *)sender;
//I have removed this line... due to the fact that I don't want to
//implement your arrays.
//self.selectedImage = [_images objectAtIndex:myButton.tag];
//deselecting all
for (UIButton *button in self.buttons)
{
button.selected = NO;
//[button setImage:nil forState:UIControlStateNormal];
}
if (myButton.selected) {
[sender setSelected:NO];
}else {
UIImage *bgImage = [UIImage imageNamed:CHECKMARK_IMAGE];
[sender setImage:bgImage forState:UIControlStateSelected];
[sender setSelected:YES];
}
// NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// [prefs setInteger:myButton.tag forKey:#"slot1"];
//getting index of button in array
NSInteger index = 0;
NSInteger foundIndex = -1;
for (UIButton *button in self.buttons)
{
if (button == myButton)
{
foundIndex = index;
}
index++;
}
if (foundIndex >= 0)
{
[[NSUserDefaults standardUserDefaults] setInteger:foundIndex forKey:#"selected1"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
[self performSelector:#selector(highlightButton:) withObject:sender afterDelay:0.0];
// [self dismissModalViewControllerAnimated:NO];
}
// ------------------------------------------------------------
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (IBAction)closeButtonClicked:(UIBarButtonItem *)sender
{
[self dismissModalViewControllerAnimated:YES];
}
#end
Try doing this.
UIImage *bgImage = [UIImage imageNamed:#"AGIPC-Checkmark-iPhone.png"];
**[myButton setSelected:NO];
[myButton setBackgroundImage:bgImage forState:UIControlStateNormal];**
UIImage *bgImage = [UIImage imageNamed:#"AGIPC-Checkmark-iPhone.png"];
**[myButton setSelected:YES];
[myButton setImage:bgImage forState:UIControlStateSelected];**
In the later part of code, you are setting the state of the button to "selected" but in the upper code, you haven't. Rather, you have disabled the button. Try the above code which I have provided. Thanks.
Just add you chekedImage as a subview on top of the button when user clicks the button
UIImage *button = [UIImage imageNamed:#"cat.png"];
[myButton setBackgroundImage:bgImage forState:UIControlStateNormal];
//add target button clicked
-(void)buttonClicked : (id)sender{
if(toogleSwitch){
[button addSubview:checkedimageView]; // Just the checked image icon
}
else{
[imageview removeFromSuperview];
}
}
What you are trying to do will only work when you have
resources of two types for all your images.
1) The image itself
2) Image with checked box as transparent layer.
I am using iCarousel as shownh here with carousel type Liner Carousel and implemented delete functionalty .I am able to delete the image in carousel and when I attempt to delete any other iomage in the visible screen It is moved to carousel frame and deleted.
I need to delete the image from its original position.
- (void)loadView {
[super loadView];
self.view.backgroundColor = [UIColor blackColor];
carousel = [[iCarousel alloc] initWithFrame:CGRectMake(-130,300, 320, 100)];
carousel.dataSource = self;
carousel.delegate=self;
carousel.type = iCarouselTypeLinear;
carousel.scrollEnabled=YES;
imageView=[[UIImageView alloc]initWithFrame:CGRectMake(60, 50, 200, 200)];
[self.view addSubview:imageView];
}
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
UIImage *image = [imagesArray objectAtIndex:index];
UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0,0, 60, 60);
[button setBackgroundImage:image forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.titleLabel.font = [button.titleLabel.font fontWithSize:50];
[button addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
button.tag=index;
NSLog(#"tag is %d",button.tag);
UIButton *deleteButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
deleteButton.frame= CGRectMake(50, -5, 20 ,20);
UIImage *img = [UIImage imageNamed:#"close.png"];
[deleteButton setImage:img forState:UIControlStateNormal];
[deleteButton addTarget:self action:#selector(deleteButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[button addSubview:deleteButton];
return button;
}
-(void)deleteButtonClicked:(int )sender
{
NSInteger currentIndex = carousel.currentItemIndex;
[carousel removeItemAtIndex:currentIndex animated:YES];
}
Please help me out.
You shouldn't delete the item at the carousel.currentItemIndex because that is not the item corresponding to the button you clicked, that's just the currently centred item in the carousel.
To get the correct item index for the button you clicked, do this:
-(void)deleteButtonClicked:(id)sender
{
//get the index of the item view containing the button that was clicked
NSInteger index = [carousel indexOfItemViewOrSubview:sender];
//update the data model (always do this first)
[imagesArray removeObjectAtIndex:index];
//remove item from carousel
[carousel removeItemAtIndex:index animated:YES];
}
Try this:
NSInteger index = carousel.currentItemIndex;
[carousel removeItemAtIndex:index animated:YES];
[imagesArray removeObjectAtIndex:index];
add this also:
- (void)awakeFromNib
{
if (self) {
//set up carousel data
wrap = NO;
}
}
or make your
carousel.type = iCarouselTypeCustom;
to
carousel.type = iCarouselTypeLinear;
then implement this: [carousel reloadData];
I want to create uibuttons dynamically. so i for loop to create button with tag and added to view.
all buttons performs the same action with respect to its tag value... but i want to change the propery of the button. Therefore i need to get the uibutton using the tag value...
my code...
UIButton *button2;
//view did load
int width = 30;
for(int i = 1; i <= 5; i++)
{
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self action:#selector(ratingAction:) forControlEvents:UIControlEventTouchUpInside];
[button2 setBackgroundImage:[UIImage imageNamed:#"star1.png"] forState:UIControlStateNormal];
button2.tag = i;
button2.backgroundColor = [UIColor clearColor];
button2.frame = CGRectMake(width, 78, 15, 15);
[self.view addSubview:button2];
width = width +30;
}
-(void)ratingAction:(id*)sender
{
// here using the tag value i want to get the button and change the background image….
// for example i want to change the background for tag values 1,3,6,7 ,8…
}
Use viewWithTag function of UIView to access your UIButton using the tag value.
See in Documentation viewWithTag
Use it as below.
UIButton* myButton = (UIButton*)[mySuperView viewWithTag:1];
UIButton* myButton = (UIButton*)[mySuperView viewWithTag:3];
UIButton* myButton = (UIButton*)[mySuperView viewWithTag:6];
.........
-(void)ratingAction:(id*)sender
{
// here using the tag value i want to get the button and change the background image….
// for example i want to change the background for tag values 1,3,6,7 ,8…
if ([sender isKindOfClass:[UIButton class]])
{
UIButton *temp=(UIButton*)sender;
if ([temp tag]==1 || [temp tag]==3 || [temp tag]==6 || [temp tag]==7 )
{
[temp setBackgroundColor:[UIColor redColor]];
}
}
}
Check this code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
int y = 100;
for (int i=0; i<=5; i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80, y, 160, 40);
[button setTitle:[NSString stringWithFormat:#"Button-%i", i] forState:UIControlStateNormal];
// [button set
[self.view addSubview:button];
y=y+60;
}
}
-(void)aMethod:(id)sender{
UIButton *button = sender;
int y = 100;
int i = 5;
for (int x=0; x<=i; x++) {
NSString *frameString = [NSString stringWithFormat:#"{{80, %i}, {160, 40}}", y];
if ([NSStringFromCGRect(button.frame) isEqualToString:frameString]) {
NSLog(#"button %i clicked..", x);
}
y= y+60;
}
}
how do i make these buttons so that only one can be used at a time? Im not getting any errors right now when i run btw. Im just looking for a solution to my challenge. Thanks for any help
they are generated in a for loop like this:
for (int l=0; l<list.length; l++) {
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton setTag:l];
CGRect buttonRect = CGRectMake(11+charact*20, -40 + line*50, 18, 21);
aButton.frame = buttonRect;
[aButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[aButton setTitle:#" " forState:UIControlStateNormal];
[gameScroll addSubview:aButton];
}
And then the action for when a button is clicked is:
- (void) buttonClicked:(UIButton *)sender {
int tag = sender.tag;
if (sender.selected == TRUE) {
[sender setSelected:FALSE];
[sender setBackgroundColor:[UIColor clearColor]];
}
else if (sender.selected == FALSE) {
[sender setSelected:TRUE];
[sender setBackgroundColor:[UIColor redColor]];
}
}
right now everything works but i want it to know if theres already a button selected and deselect that other button, or else to automatically deselect any time the user clicks outside of the range of that button
thanks in advance
I would suggest to put all ur buttons to Array in your button initialisation
NSMutableArray* buttons = [NSMutableArray arrayWithCapacity: list.length];
for (int l=0; l<list.length; l++) {
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton setTag:l];
CGRect buttonRect = CGRectMake(11+charact*20, -40 + line*50, 18, 21);
aButton.frame = buttonRect;
[aButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[aButton setTitle:#" " forState:UIControlStateNormal];
[gameScroll addSubview:aButton];
[buttons addObject: aButton];
}
and every time buttonClicked triggered, then do your logic:
for (UIButton* button in buttons)
{
if (button != sender)
{
[button setSelected: FALSE];
[button setBackgroundColor:[UIColor redColor]];
}
}
int tag = sender.tag;
if (sender.selected == TRUE) {
[sender setSelected:FALSE];
[sender setBackgroundColor:[UIColor clearColor]];
}
else if (sender.selected == FALSE) {
[sender setSelected:TRUE];
[sender setBackgroundColor:[UIColor redColor]];
}
hope helps :)
You can store currently selected button in a separate variable and deselect it in buttonClicked: method:
- (void) buttonClicked:(UIButton *)sender {
int tag = sender.tag;
currentButton.selected = NO;
if (currentButton != sender){
currentButton = sender;
currentButton.selected = YES;
}
else{
currentButton = nil;
}
}
Also you can specify background colour for each state in button itself so you actually don't need to change it each time manually
If you also want to deselect your button when user just touches the screen you can implement touchesEnded:withEvent: in your view controller and reset currentButton in it (that method will get called if no other control intercept the touch event - so it may not be sufficient in all cases)
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event{
currentButton.selected = NO;
currentButton = nil;
}
I have created buttons dynamically and now I want to set the background for a particular index of the buttons.
Here is my sample snippet:
In the interface file:
UIButton *answerBtn;
#property (nonatomic, retain) UIButton *answerBtn;
for(int i = 0; i < [myArray count]; i++) {
answerBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[answerBtn setFrame:CGRectMake(30, x, 260, 40)];
answerBtn.tag = i;
[answerBtn setTitle:[answerList objectAtIndex:i] forState:UIControlStateNormal];
[self.view addSubview: answerBtn];
}
In my case, I want to set the button background in different methods.
-(void) custom Method
{
if(indexValue == correctIndex) // Values are 2
{
// so I want to set the background image for the second button
[answerBtn setBackgroundImage:[UIImage imageNamed:#"selected_correct_answer.png"] forState:UIControlStateNormal];
}
}
But it doesn't set the corresponding index, so how can I do that?
Try this
for(int i = 0 ; i < [myArray count] ; i++ )
{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setTag:i];
[btn setFrame:CGRectMake(30, x, 260, 40)];
[btn addTarget:self action:#selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
- (IBAction) btnClicked::(id)sender
{
UIButton *btnTapped=(UIButton *)sender;
for(UIView *btn in self.view.subviews)
{
if([btn isKindOfClass:[UIButton class]])
{
UIButton *btnComp = (UIButton*)btn;
if(btnComp.tag == btnTapped.tag)
[btnComp setBackgroundImage:[UIImage imageNamed:#"selected_correct_answer.png" forState:UIControlStateNormal];
else
[btnComp setBackgroundImage:[UIImage imageNamed:#"default_image.png" forState:UIControlStateNormal];
}
}
}
Use -(void)custom:(id)sender instead of -(void)custom.
In the sender you can have the index of the button.
UIButton *answerBtn = (UIButton *)[self objectWihTag:1]