Question: How do I target one of many dynamically created UIButtons so I can change its properties?
Background: I have a storyboard with a UIViewConroller. When this UIVC loads a UIScrollView is added, to which a UIImageView is placed that has an exhibition floor plan. Each exhibitor has an entry in a database that contains its location on the floor plan. When the UIVC is loaded a loop is run for all exhibitors and each one has a UIButton drawn on the UIIV. When a UIB is clicked the button background colour is changed (to confirm which exhibitor has been selected) and a UIAlertView is shown with information about that exhibitor. When the UIAV's 'cancel' (ok) button is pressed the UIAV closes and the background highlight colour that was applied previously should be removed but here is where I am having the problem. I am unable to target the UIButton so I can change its background colour.
What I have tried so far: As each button is created I am giving it a tag and a title and recording both in an array. When the 'cancel' button is pressed on the UIAlertView I have tried checking the tag in the array but I still cannot actually target the UIButton.
I was thinking something like this:
// obviously not correct syntax but the kind of thing I want
[exhibitorBtn(tag) setBackgroundColor:[UIColor greenColor]];
So, say I have 12 UIButtons all called exhibitorBtn but with different titles and tags:
Object ----- Name ---------- Title -------- Tag
UIButton -- exhibitorBtn -- Glaxo ------ 1
UIButton -- exhibitorBtn -- Porsche --- 2
UIButton -- exhibitorBtn -- Rolex ------- 3 < How would I target that button's properties?
Edit - added the code that creates the buttons just to clarify:
for (NSDictionary *dict in exhibitorStandArray) {
NSInteger currentPosition = [exhibitorStandArray indexOfObject:dict];
NSLog(#"Position in array = %li", (long)currentPosition);
if (![dict[#"locCoords"] isEqual: #""]) {
NSInteger buttonTag = [exhibitorStandArray indexOfObject:dict];
NSString *standNo = dict[#"locStandNo"];
NSMutableDictionary *buttonDictionary = [[NSMutableDictionary alloc] init];
[buttonDictionary setObject:[NSNumber numberWithInteger:buttonTag] forKey:#"buttonTag"];
[buttonDictionary setObject:standNo forKey:#"buttonStandNo"];
[_masterButtonList addObject:buttonDictionary];
NSString *locCoords = dict[#"locCoords"];
NSArray *tempArray =[locCoords componentsSeparatedByString:#","];
tlcTop = [[tempArray objectAtIndex:0] integerValue];
tlcLeft = [[tempArray objectAtIndex:1] integerValue];
brcTop = [[tempArray objectAtIndex:2] integerValue];
brcRight = [[tempArray objectAtIndex:3] integerValue];
buttonWidth = brcRight - tlcLeft;
buttonHeight = brcTop - tlcTop;
testBtn = [UIButton buttonWithType:UIButtonTypeCustom];
testBtn.frame = CGRectMake(tlcTop, tlcLeft, buttonHeight, buttonWidth);
testBtn.titleLabel.text = standNo;
testBtn.tag = buttonTag;
NSLog(#"UIButton Title = %#", testBtn.titleLabel.text);
NSLog(#"UIButton Tag = %li", (long)testBtn.tag);
testBtn.titleLabel.hidden = YES;
[testBtn addTarget:self action:#selector(displayInfo:) forControlEvents:UIControlEventTouchUpInside];
[_buttonArray addObject:testBtn];
[_imageView addSubview:testBtn];
}
}
Why can't you just use viewWithTag:
UIButton * button = (UIButton *)[self.scrollView viewWithTag:tag];
Your code probably looks something like this:
for (int i = 0; i < 5; i++)
{
UIButton *exhibitorBtn = [[UIButton alloc] initWithFrame:etc..];
exhibitorButton.tag = i;
[scrollView addSubview:exhibitorBtn];
}
Just change the loop so every button will be added to an array, too. Declare a NSMutableArray as a property: #property (strong, nonatomic) NSMutableArray *buttonsArray;
And #synthesize and initialise it in your init method. buttonsArray = [[NSMutableArray alloc] init]
Then, change the loop like I said above:
for (int i = 0; i < 5; i++)
{
UIButton *exhibitorBtn = [[UIButton alloc] initWithFrame:etc..];
exhibitorButton.tag = i;
[buttonsArray addObject:exhibitorBtn];
[scrollView addSubview:exhibitorBtn];
}
Finally, when you want to access the buttons:
for (int i = 0; i < [buttonsArray count]; i++)
{
UIButton *button = [buttonsArray objectAtIndex:i];
if (button.tag == 3) { // This is the button you wanted to target!
[button setHidden:YES];
}
}
Let's make it clear: you did set target and action of UIButton to controller's IBAction method and get the button as sender argument. Now you show UIAlertView and after it is dismissed, you want to send some message to that button, right?
Another method is to set delegate property for UIAlertView and respond to – alertView:clickedButtonAtIndex: delegate method. Trouble is that sender is lost at that point. You may use objc_setAssociatedObject to associate UIButton with UIAlertView and the retrieve it back when delegate method fires:
#import <objc/runtime.h>
static char myButtonKey = 0; // to use address as a key (value is irrelevant)
- (IBAction)buttonDidClick:(id)button
{
UIAlertView *alertView = <setup alert>;
[alertView setDelegate:self];
objc_setAssociatedObject(alertView, &myButtonKey, button, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
<show alert>;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
UIButton *thatButton = objc_getAssociatedObject(alertView, &myButtonKey);
<use thatButton>;
}
Try to create button in this way and add selector to them :
for (int i = 0; i < 5; i++)
{
UIButton *button = [[UIButton alloc] initWithFrame:CGRectZero];
button.tag = i;
[button addTarget:self
action:#selector(buttonPressedMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Show View" forState:UIControlStateNormal];
// add button to subview here
}
In method, just do whatever, you want to do :
- (void) buttonPressedMethod : (id) sender {
UIButton *selectedButton = (UIButton *)sender;
if (selectedButton.tag == 0) {
}
else if (selectedButton.tag == 1) {
}
else {
}
}
Related
I am developing an IOS App. I am creating a text field and a button dynamically, and I want to get textfield's text on button click, but I'm getting an error:
[UIView setText:]: unrecognized selector sent to instance
Here is my code:
- (IBAction)customFieldAdd:(id)sender{
[_addfieldArray addObject:_field];
x = 10;
y = 10;
for( int i = 0; i < [_addfieldArray count]; i++ ) {
UITextField *copyfield = [[UITextField alloc]initWithFrame:CGRectMake(5.0, x + _field.frame.size.height, 195.0f, 30.0f)];
[copyfield setDelegate:self];
[copyfield setTag:i];
[_filterPossibleValueView addSubview:copyfield];
x = x+_field.frame.size.height+10;
UIButton *copyAddButton = [[UIButton alloc]initWithFrame:CGRectMake(202.0f, y + _addField.frame.size.height, 30.0f, 30.0f)];
[copyAddButton setTag:i];
[copyAddButton addTarget:self action:#selector(customFieldDelete:) forControlEvents:UIControlEventTouchUpInside];
[_filterPossibleValueView addSubview:copyAddButton];
y = y+_addField.frame.size.height+10;
count++;
}
}
- (IBAction)customFieldDelete:(id)sender{
UIButton *button = (UIButton*)sender;
NSInteger index = button.tag;
// [_addfieldArray removeObjectAtIndex:index];
UITextField *field = [_filterPossibleValueView viewWithTag:index];
NSString *myText = field.text;
}
The default value for the tag property is 0, and you are setting that value to one of the text fields. So, when you try to get the view with tag == 0, it will have more than one view with that tag.
You should use an offset when setting the tag:
[copyfield setTag:kOffset + i];
...
[copyAddButton setTag:kOffset*2 + i]; // note that the button and the text field should not have the same tag either
where kOffset is defined (for example) like this:
let kOffset: Int = 1000
Then, to get the text field's text, you can use:
NSInteger tag = button.tag - kOffset;
UITextField *field = [_filterPossibleValueView viewWithTag:tag];
NSString *myText = field.text;
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
On first Page i am having some buttons , if i press any button it will move to Second page , here if i press back button in the navigation bar it will move to first page
i have created the buttons dynamically based on the array count ,i want to show the selected button when i move back to first page , how can i do this ?Please help me to do this .here is the code that i have used for creating buttons
int buttonheight = 30;
int horizontalPadding = 20;
int verticalPadding = 20;
int totalwidth = self.view.frame.size.width;
int x = 10;
int y = 150;
for (int i=0; i<array.count; i++)
{
NSString* titre = [array objectAtIndex:i];
//
CGSize contstrainedSize = CGSizeMake(200, 40);//The maximum width and height
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:20.0], NSFontAttributeName,
nil];
CGRect frame = [titre boundingRectWithSize:contstrainedSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDictionary context:nil];
int xpos = x + CGRectGetWidth(frame);
if (xpos > totalwidth) {
y =y +buttonheight+ verticalPadding;
x = 10;
}
UIButton * word= [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.word = word;
NSLog(#"%#", NSStringFromCGRect(frame));
word = [UIButton buttonWithType:UIButtonTypeRoundedRect];
word.frame = CGRectMake(x, y, CGRectGetWidth(frame)+5, CGRectGetHeight(frame));
[word setTitle:titre forState:UIControlStateNormal];
word.backgroundColor = [UIColor colorWithRed:30.0/255.0 green:134.0/255.0 blue:255.0/255.0 alpha:1.0];
[word setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[word setTag:i];
[word addTarget:self action:#selector(btn1Tapped:) forControlEvents:UIControlEventTouchUpInside];
word.layer.borderColor = [UIColor blackColor].CGColor;
word.layer.borderWidth = 1.0f;
word.layer.cornerRadius = 5;
[self.view addSubview:word];
x =x+horizontalPadding+CGRectGetWidth(frame);
}
- (IBAction)btn1Tapped:(id)sender {
NSString *btnTitle;
btnTitle = [(UIButton *)sender currentTitle];
NSLog(#"%#",self.title);
ReasonViewController *ReasonVC = [self.storyboard instantiateViewControllerWithIdentifier:#"ReasonVC"];
ReasonVC.btnTitle = btnTitle;
NSLog(#"%#",self.imageArray);
ReasonVC.imageArray1 = self.imageArray;
[self.navigationController pushViewController:ReasonVC animated:YES];
}
=====Appdelegate.h========
#property (assign, nonatomic) long int btnTag;
=======CategoryViewController.h============
import "AppDelegate.h"
#interface CategoryViewController : UIViewController
{
AppDelegate *appdel;
}
===========CategoryViewController.m=======
add code
if(appdel.btnTag == word.tag)
{
word.selected = YES;
}
below [word setTag:i]; code
then add
UIButton *btn = (UIButton *) sender;
appdel.btnTag = btn.tag;
in - (IBAction)btn1Tapped:(id)sender method
The UIButton object has different states included the "Selected state". You can set different background image or title for each state you want. When you press it you can change its state like this:
//After you inited your UIButton Object do this:
[button setBackgroundImage:selectedBGImage forState:UIControlStateSelected];
[button setBackgroundImage:deselectedBGImage forState:UIControlStateNormal];
//You can also find the title change method for state accordingly
- (void)buttonAction:(UIButton *)sender
{
sender.selected = !sender.selected;
//TODO
}
So, when you pop back, the button will keep its "selected" state.
You have to store button tag in appdelegate and while creating button check with button tag/i values and do selected. please see below code
in AppDelegate.h
#property (assign, nonatomic) int btnTag;
create an object of AppDelegate on your current ViewController then
AppDelegate *appdel = (AppDelegate *)[[UIApplication sharedApplication] delegate];
int buttonheight = 30;
.
.
.
[word setTag:i];
if(word.tag == appdel.btnTag)//appdel is object of AppDelegate
{
word.selected = YES;
}
[word addTarget:self action:#selector(btn1Tapped:) forControlEvents:UIControlEventTouchUpInside];
word.layer.borderColor = [UIColor blackColor].CGColor;
word.layer.borderWidth = 1.0f;
word.layer.cornerRadius = 5;
[self.view addSubview:word];
x =x+horizontalPadding+CGRectGetWidth(frame);
}
- (IBAction)btn1Tapped:(id)sender {
UIButton *btn = (UIButton *) sender;
appdel.btnTag = btn.tag;
NSString *btnTitle;
btnTitle = [(UIButton *)sender currentTitle];
NSLog(#"%#",self.title);
ReasonViewController *ReasonVC = [self.storyboard instantiateViewControllerWithIdentifier:#"ReasonVC"];
ReasonVC.btnTitle = btnTitle;
NSLog(#"%#",self.imageArray);
ReasonVC.imageArray1 = self.imageArray;
[self.navigationController pushViewController:ReasonVC animated:YES];
}
enter image description here
I am getting like below screenshot , if i tapped any button it will move to next page and the backgroundcolor is changed to red color,and come back to same page by clicking back and now i tapped another button it is also showing in red color.
I have use this two lines in button action method :
UIButton *btn = (UIButton *) sender;
[btn setBackgroundColor:[UIColor redColor]];
Let me explain my project first. I have some data in my SQLIte DB table called "note".
In "note" table I have these fields: id, noteToken, note.
What I am doing here is load all the note in an NSMUtableArray from that table. And create UIButton according to that array content number and add those buttons in a UIScrollView as subView. The number of buttons and width of scrollview generate auto according to the number of content of that array. Now, when some one tap one of those Buttons, it will bring him to a next viewController and show him the corresponding note details in that viewController.
I do the same thing with another NSMUtableArray, but these time it read all the id from the "note" table. It equally generate new delete button in the same UIScrollView. But if some one tap on these delete button it will delete that particular note from the table "note" of SQLIte DB. AND RELOAD THE UIScrollView. All are done except the RELOAD THE UIScrollView part. This is what I want. I tried with all exist solution but don't know why it's not working.
Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
self.noteToken = [NSString stringWithFormat:#"%#%#", fairId, exibitorId];
scrollViewNoteWidth = 100;
[scrollViewNote setScrollEnabled:YES];
[scrollViewNote setContentSize:CGSizeMake((noteButtonWidth * countNoteButtonArray) + scrollViewNoteWidth, 100)];
sqLite = [[SQLite alloc] init];
[self.sqLite callDataBaseAndNoteTableMethods];
self.noteButtonArrayy = [[NSMutableArray alloc] init];
noteButtonArrayy = [self.sqLite returnDataFromNoteTable:noteToken];
[self LoadNoteButtonAndDeleteButton:noteButtonArrayy];
}
//////////////*----------------------- Note Section (Down) -----------------------*//////////////
-(void) LoadNoteButtonAndDeleteButton:(NSMutableArray *) noteButtonArray
{
sQLiteClass = [[SQLiteClass alloc] init];
noteButtonArrayToShowNoteButton = [[NSMutableArray alloc] init];
/*--------------- Load the noteButton & pass note (Down)---------------*/
for (int i = 0; i < [noteButtonArray count]; i++)
{
sQLiteClass = [noteButtonArray objectAtIndex:i];
// NSString *ids = [NSString stringWithFormat:#"%d", sQLiteClass.idNum];
NSString *nt = sQLiteClass.note;
[noteButtonArrayToShowNoteButton addObject:nt];
}
[self ShowNoteButtonMethod:noteButtonArrayToShowNoteButton];
/*--------------- Load the noteButton & pass note (Up)---------------*/
/*--------------- Load the deleteButton & pass id (Down)---------------*/
noteButtonArrayToDeleteNoteButton = [[NSMutableArray alloc] init];
for (int i = 0; i < [noteButtonArray count]; i++)
{
sQLiteClass = [noteButtonArray objectAtIndex:i];
// Convert int into NSString
NSString *ids = [NSString stringWithFormat:#"%d", sQLiteClass.idNum];
[noteButtonArrayToDeleteNoteButton addObject:ids];
}
[self ShowNoteDeleteButtonMethod:noteButtonArrayToDeleteNoteButton];
/*--------------- Load the deleteButton & pass id (Down)---------------*/
}
-(void) ShowNoteButtonMethod:(NSMutableArray *) btnarray
{
countNoteButtonArray = [btnarray count];
// For note button
noteButtonWidth = 60;
noteButtonXposition = 8;
for (NSString *urls in btnarray)
{
noteButtonXposition = [self addNoteButton:noteButtonXposition AndURL:urls];
}
}
-(int) addNoteButton:(int) xposition AndURL:(NSString *) urls
{
noteButton =[ButtonClass buttonWithType:UIButtonTypeCustom];
noteButton.frame = CGRectMake(noteButtonXposition, 8.0, noteButtonWidth, 60.0);
[noteButton setImage:[UIImage imageNamed:#"note.png"] forState:UIControlStateNormal];
[noteButton addTarget:self action:#selector(tapOnNoteButton:) forControlEvents:UIControlEventTouchUpInside];
[noteButton setUrl:urls];
noteButton.backgroundColor = [UIColor clearColor];
[self.scrollViewNote addSubview:noteButton];
noteButtonXposition = noteButtonXposition + noteButtonWidth + 18;
return noteButtonXposition;
}
-(void)tapOnNoteButton:(ButtonClass*)sender
{
urlNote = sender.url;
[self performSegueWithIdentifier:#"goToNoteDetailsViewController" sender:urlNote];
}
-(void) ShowNoteDeleteButtonMethod:(NSMutableArray *) btnarray
{
countNoteButtonArray = [btnarray count];
// For delete button
deleteNoteButtonWidth = 14;
deleteNoteButtonXposition = 31;
for (NSString *idNumber in btnarray)
{
deleteNoteButtonXposition = [self addDeleteButton:deleteNoteButtonXposition AndURL:idNumber];
}
}
-(int) addDeleteButton:(int) xposition AndURL:(NSString *) idNumber
{
deleteNoteButton =[ButtonClass buttonWithType:UIButtonTypeCustom];
deleteNoteButton.frame = CGRectMake(deleteNoteButtonXposition, 74.0, deleteNoteButtonWidth, 20.0);
[deleteNoteButton setImage:[UIImage imageNamed:#"delete.png"] forState:UIControlStateNormal];
[deleteNoteButton addTarget:self action:#selector(tapOnDeleteButton:) forControlEvents:UIControlEventTouchUpInside];
[deleteNoteButton setIdNum:idNumber];
deleteNoteButton.backgroundColor = [UIColor clearColor];
[self.scrollViewNote addSubview:deleteNoteButton];
deleteNoteButtonXposition = deleteNoteButtonXposition + deleteNoteButtonWidth + 65;
return deleteNoteButtonXposition;
}
-(void)tapOnDeleteButton:(ButtonClass*)sender
{
idNumb = sender.idNum;
[self.sqLite deleteData:[NSString stringWithFormat:#"DELETE FROM note WHERE id IS '%#'", idNumb]];
// NSLog(#"idNumb %#", idNumb);
//[self.view setNeedsDisplay];
//[self.view setNeedsLayout];
//[self LoadNoteButtonAndDeleteButton];
//[self viewDidLoad];
// if ([self isViewLoaded])
// {
// //self.view = Nil;
// //[self viewDidLoad];
// [self LoadNoteButtonAndDeleteButton];
// }
}
//////////////*----------------------- Note Section (Up) -----------------------*//////////////
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"goToNoteDetailsViewController"])
{
NoteDetailsViewController *noteDetailsViewController = [segue destinationViewController];
[noteDetailsViewController setUrl:sender];
}
}
Here's the screen shot:
Here we can feel the difference between UIScrollView and UICollectionView, however UICollectionView is made up of UIScrollView, UICollectionView can be reload and adjust its content accordingly, where UIScrollView can't.
Ok, now in your case, you've to reload (refresh) your scroll view, which is not possible as we can with UICollectionView or UITableView.
You've two options,
Best option (little tough) : replace UIScrollView with UICollectionView - will take some of your time, but better for reducing code complexity and good performance of your app.
Poor option (easy) : Stay as it with UIScrollView - when you want to reload, delete each subview from it, and then again show and load everything. Highly not recommended.
IMHO, you should go with best option.
I have a UIViewController with a tableView in it with CustomCells, the CustomCell load a PLAY Button for some of the cells, this button are generated within the CustomCell.m
- (UIButton *)videoButton {
if (!videoButton) {
videoButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
videoButton.frame = CGRectMake(120, 319, 50, 30);
[videoButton setTitle:#"Play" forState:UIControlStateNormal];
[videoButton addTarget:self action:#selector(PlayClicked:) forControlEvents:UIControlEventTouchUpInside];
videoButton.backgroundColor= [UIColor clearColor];
[self.contentView addSubview:videoButton];
}
playIMG.hidden = false;
return videoButton;
}
- (IBAction)PlayClicked:(id)sender {
TableView *tvvc = [[TableView alloc] init];
[tvvc PlayBtnClicked:[NSString stringWithFormat:#"%d", [sender tag]]];
}
in my TableView.m
- (IBAction)PlayBtnClicked:(id)sender {
NSString *tag = [NSString stringWithFormat:#"%#", sender]; //OK
int tagNumber = [tag intValue]; //OK
NSString *Media = [arrayID objectAtIndex:tagNumber]; //Not Getting Result !
NSLog(#"%#", arrayID); //Array is empty when logging it from this action
}
arrayID is NSMutableArray
arrayID = [[NSMutableArray alloc] init];
[arrayID addObject#"123"];
[arrayID addObject#"321"];
[arrayID addObject#"231"];
soo i checked the array by adding an action button in my TableView to log the array and its not empty.
how can i fix the empty array which is actually not empty ?
I solved the problem in much easier way than the delegate thing
removed
[videoButton addTarget:self action:#selector(PlayClicked:) forControlEvents:UIControlEventTouchUpInside];
and the action in the custom cell .m file
- (IBAction)PlayClicked:(id)sender {
TableView *tvvc = [[TableView alloc] init];
[tvvc PlayBtnClicked:[NSString stringWithFormat:#"%d", [sender tag]]];
}
in the tableView.m i added edited the action i want to link to this
- (IBAction)PlayBtnClicked:(UIButton*)button {
NSLog(#"Button Clicked Tag: %d", button.tag);
}
and in the cellForRowAtIndexPath method i added the action to the button in the custom cell
if ([MediaType isEqualToString:#"video"]) {
cell.videoButton.hidden = NO;
cell.videoButton.tag = indexPath.row;
[cell.videoButton addTarget:self action:#selector(PlayBtnClicked:) forControlEvents:UIControlEventTouchUpInside];//here linking the action to the button
cell.playIMG.hidden = NO;
}
now everything is working very well :)
The array isn't your problem - you're breaking the model-view-controller nature of the table view controller and its cells. If you want a control in the cell to call a method in the table view controller, make the table view controller the delegate of the cell, and call the delegate method from the cell's button.
If the code you've posted is correct, then you're creating a new table view instance in the PlayClicked method, which is definitely not the way to do it.
As a minor stylistic point, the Cocoa convention of method naming is camelCase, with a lower-case initial letter.
I have created 3 buttons at my top.take the offset of them and giving them same IBAction.
I want to change images at below according to the which button is pressed.
Further i have to pass these images to the another ViewControler, Here
i have got 3 arrays named bundle1 , bundle2 , bundle3 . in each array i have set of 5 images, in my Viewdidload as below,
bundle1 = #[#"1.png",#"2.png", #"3.png", #"4.png" ,#"5.png"];
bundle2 = #[#"6.png", #"7.png", #"8.gif",#"9.jpeg", #"10.jpeg" ];
bundle3 = #[#"11.jpg", #"12.jpg" ,#"13.jpeg", #"14.jpeg", #"15.jpeg"];
now i had take mutabledictionary, which had upper 3 arrays and i had give them a specific key
as below.
mutdict = [[NSMutableDictionary alloc] initWithObjectsAndKeys: bundle1 , #"key1" , bundle2 , #"key2" , bundle3 , #"key3" ,nil];
Now below is the code for IBAction of Upper 3 buttons, (Which is the same for all 3 buttons).
-(IBAction)morebtn:(id)sender
{
for (UIView *subview in [scroll subviews])
{
[subview removeFromSuperview];
}
arraydata = [[NSMutableArray alloc] init];
if ([sender tag] == 1) {
NSLog(#"hey btn1 clicked");
for (UIImage *b in arraydata)
{
[arraydata removeAllObjects];
}
arraydata = [mutdict valueForKey:#"key1"];
}
if ([sender tag] == 2) {
NSLog(#"hey btn2 clicked");
for (UIImage*b in arraydata)
{
[arraydata removeAllObjects];
}
arraydata = [mutdict valueForKey:#"key2"];
}
if ([sender tag] == 3) {
NSLog(#"hey btn3 clicked");
for (UIImage*b in arraydata)
{
[arraydata removeAllObjects];
}
arraydata = [mutdict valueForKey:#"key3"];
}
int x=10,y=300;
for (int k=0; k<arraydata.count; k++) {
NSLog(#"main called");
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:[UIImage imageNamed:[arraydata objectAtIndex:k]] forState:UIControlStateNormal];
btn.tag=k;
btn.frame=CGRectMake(x, y, 100, 100);
[btn addTarget:self action:#selector(btn4images1:) forControlEvents:UIControlEventTouchUpInside];
x+=100;
scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 300, self.view.frame.size.width, 200)];
scroll.contentSize = CGSizeMake(self.view.frame.size.width , 200);
[scroll addSubview:btn];
[self.view addSubview:scroll];
}
}
in upper code i trace which button is pressed and according to it i wil give inages in my NSArray named arraydata.
when i first time click on the all 3 upper buttons they show me image related to their array, but when i second time click on button1 (placed on the top), The images related to button3 are also shown in the Buttonbackground (palced at below part).
so on clicking button1 in below part button background images are overlaped. Seems like my NSMutableDictionary stores the data of last array. don't know what exactly happen.