【问题标题】:how to get the data from API to tableview with segmented control actions?如何使用分段控制操作将数据从 API 获取到 tableview?
【发布时间】:2015-12-17 11:27:31
【问题描述】:

我有一个视图控制器,我添加了 1tableview 和分段控制。 在默认情况下,segmented=0 被选中并将数据加载到使用 API 加载的数据的 tableview 中。 当我在同一个表视图中选择分段 = 1、2、3、4、5 时,如何使用 API 加载数据。 这是我的代码

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 ?

【问题讨论】:

    标签: ios uitableview uisegmentedcontrol


    【解决方案1】:
    -(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
    
    } 
    }
    

    【讨论】:

    • 输入 int 索引;在 .h 和 viewdidload 中 index=0;
    • 不需要将objectforkey值放入cellforrowatindex吗?我将该值存储在数组中!
    • 现在检查我已经改变了。你也可以投票回答
    猜你喜欢
    • 2019-12-02
    • 2021-06-20
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    相关资源
    最近更新 更多