简体   繁体   中英

Change tableview datasource with two UIButtons

having a UITableView and its data source is an NSMutableArray which is actually an parsed XML file; In the same view I have two UIButtons with the same action method, how I'm able to toggle the tableview's datasource?

When pressing A button to load dataSource1 and B to load dataSource2

- (void)buttonsAction: (id)sender {
    
    BOOL activateSecond = _firstButton.selected;
    _firstButton.selected = !activateSecond;
    _secondButton.selected = activateSecond;
}

    dataSource1 = [[NSMutableArray alloc]init];
    nodecontent = [[NSMutableString alloc]init];
        
    NSString *xmlURL = @"http://mydomain.com/file.xml";
    NSData *xmlData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:xmlURL]];
    xmlParserObject = [[NSXMLParser alloc]initWithData:xmlData];
    [xmlParserObject setDelegate:self];
    [xmlParserObject parse];
    [xmlData release];

Any clue?

Step 1 : load data into your arrays ( if you are fetching from xml/web do that, I have implemented static here )

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.arOne=[NSArray arrayWithObjects:@"Sagar",@"Amit",@"Nimit",@"Paresh",@"Rakesh",@"Yogesh", nil];
    self.arTwo=[NSArray arrayWithObjects:@"Supreeth",@"Deepthy",@"Ankit",@"Sandeep",@"Gomathy", nil];
    [self.tableView reloadData];
}

step 2 : place conditional coding for tableViewCell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.textLabel.text=[(self.btnTapped.selected)?self.arTwo:self.arOne objectAtIndex:indexPath.row];
    return cell;
}

step 3 : connect an action to your button ( here button is named as btnTapped )

- (IBAction)btnTitle:(id)sender {
    self.btnTapped.selected=!self.btnTapped.selected;
    [self.tableView reloadData];
}

When you click second button , remove all the elements from your data source arrays like

[dataSource1 removeAllObjects];  

And then parse the xml and add data to these arrays and when parsing get finished reload your tableView by doing

[tbl reloadData];

Hope it helps....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM