Xcode TableView showing different arrays one at a time

So, I know that if you guys do not like my question, you are going to vote for me and reduce my reputation :( But I need to study and I can not find the answer, so here again I will risk my reputation, Now to the point. All what I'm trying to do is one view with two buttons and a table view under the buttons, this table view should display a different array depending on the witch button, in other words, all I want to do is if I press the button1 button display array1 if I press button2 display array2, simple! but I e can make it work Here is an example of my code.:

- (void)viewDidLoad { array1 = [[NSArray arrayWithObjects: @"A", @"B", @"c", @"D", nil] retain]; array2 = [[NSArray arrayWithObjects: @"1", @"2", @"3", @"4", nil] retain]; } - (IBAction)btnPeriodicos:(id)sender { displayArray = 1; } - (IBAction)btnRadios:(id)sender { displayArray = 2; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (displayArray == 1) { return [array1 count]; } if (displayArray == 2) { return [array2 count]; } [self.tableView reloadData]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } // Configure the cell. cell.textLabel.textAlignment = UITextAlignmentCenter; cell.textLabel.textColor = [UIColor blackColor]; if (menuNumberInt == 1) { cell.textLabel.text = [[periodicoArray objectAtIndex:indexPath.row] retain]; } if (menuNumberInt == 2) { cell.textLabel.text = [[radioArray objectAtIndex:indexPath.row] retain]; } return cell; } 

If I place instead of if else statements either [array1 count] for numberOfRowsInSection and cell.textLabel.text = [[periodicoArray objectAtIndex: indexPath.row] save]; the application loads with filling the table with this array, so I think the table works, but how can I make my buttons change the cells of the table? any help is much appreciated. Thanks

0
source share
1 answer

You may have an iVar variable for NSArray * currentArray. In viewDidLoad, you can define your two arrays (as you do now), but then assign currentArray to the array.

Then change all tableView callbacks to work with currentArray and get rid of the if (displayArray == x) check.

in the button handlers (IBAction), assign currentArray to the appropriate array and call [tableView reloadData]. which will clear the table and call all tableView callbacks. as currentArray has changed, all callbacks will retrieve data from the corresponding array.

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1445109/


All Articles