2015-12-17 51 views
2

我有一個視圖控制器,我添加了1tableview和分段控制。 在默認情況下選擇segmented = 0並將數據加載到tableview中使用API​​加載的數據。 當我選擇分段= 1,2,3,4,5在同一個tableview如何,加載數據與API的。 這裏是我的代碼如何使用分段控制操作從API獲取數據到tableview?

view DidLoad 
{ 
[segment setSelectedSegmentIndex:0]; 
[segment addTarget:self action:@selector(segmentSelected:) forControlEvents:UIControlEventValueChanged]; 
} 

-(void)segmentSelected:(id)sender 
{ 
if (segment.selectedSegmentIndex == 0) 
{ 
    NSURLRequest *request0 = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:@"API 1"]]; 
    connection1 =[[NSURLConnection alloc]initWithRequest:request0 delegate:self]; 
    [connection1 start]; 
} 
else if (segment.selectedSegmentIndex == 1) 
    { 
     NSURLRequest *request1 = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:@"API 2"]]; 
     connection1 = [[NSURLConnection alloc]initWithRequest:request1 delegate:self]; 
     [connection1 start]; 

    } 
else if (segment.selectedSegmentIndex == 2) 
{ 
    NSURLRequest *request2 = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:@"API 3"]]; 
    connection1 = [[NSURLConnection alloc]initWithRequest:request2 delegate:self]; 
    [connection1 start]; 
} 
} 

    -(void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
if (connection==connection1) 
{ 
    NSDictionary *dic =[NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingAllowFragments error:nil]; 

    contestArray = [dic valueForKey:@"example1"]; 

    courseArray = [dic valueForKey:@"example2"]; 

    contestIdArray = [dic valueForKey:@"example3"]; 

    [progressHud hide:YES]; 
    [self.tableViewContest reloadData]; 
} 
} 

如何管理我的tableviewnumberofrows的部分?

回答

2
-(void)segmentSelected:(id)sender { 
    index = segment.selectedSegmentIndex; 
    [self.tableview reloadData]; 

//加入這一行

in tableview delegate 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 

if(index == 0){ 
return array1.count; 
} 
    if(index == 1){ 
return array2.count; 
} 
    if(index == 3){ 
return array3.count; 
} 
    if(index == 4){ 
return array4.count; 
} 
} 

中的cellForRowAtIndexPath

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    if(index == 0) { 
     cell.textfield = [array1 objectAtIndex:indexPath.row]; 
    //like that 

} 
} 
在你的代碼是什麼指數
+0

一樣的嗎? –

+0

put int index;在.h和viewdidload index = 0; – vaibby

+0

無需在cellforrowatindex中放置objectforkey值?我將這個值存儲在數組中! –

相關問題