如何为不同的分段控制索引更改数据源

How to change datasource for different segmented control index

我正在使用带有标题、phone 和电子邮件的分段控件。我正在从地址簿中获取联系人详细信息并将它们存储为字典数组。每个字典都有键 "name"、"email"、"image"、"phone"。我的要求是在点击电子邮件时仅在表格视图中显示带有电子邮件的联系人,并在段控件上点击 phone 按钮时显示带有 phones 的联系人。请帮助我实现这一目标。

只需在下面的委托方法中检查 segmentedControl 索引状态即可完成。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if segmentedControl.selectedSegmentIndex == 0 {
        // Load phone values from dictionary 
        ....
     }
    else {
        // Load email values from dictionary
        ....
    }
}

当分段控制索引改变时,不要忘记重新加载 table。

我们可以实现这个多重 ways.in 这里我使用 Tag 概念,例如

第一步

在您的 ViewDidLoad 中,设置为您的 tableview.tag=1;

第 2 步

- (IBAction)segBtnTapped:(id)sender {

  if(yourSegmentControl.selectedSegmentIndex==0){
    // email
    tableview.tag=1;
 }
 else if(segControlForColor.selectedSegmentIndex==1){
   // phone
    tableview.tag=2;
 }
else{
    // titles
    tableview.tag=3;
 }
 [yourtableView reloadData];
}

第三步

无需更改部分中的行数或任何内容,只需调用 CellForRowatIndexpathdidSelectrowatIndexpath,例如

 -(UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath
{


UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

   if(tableview.tag == 1)
  {
      //code for email  
      cell.textLabel.text =[[yourarrayName objectAtIndex:indexPath.row]objectForKey:@"email"];

  }

  else if(tableview.tag == 2)
  {
      //code for phone

cell.textLabel.text =[[yourarrayName objectAtIndex:indexPath.row]objectForKey:@"phone"];

  }

  else if(tableview.tag == 3)
  {
      //code for titles 
         cell.textLabel.text =[[yourarrayName objectAtIndex:indexPath.row]objectForKey:@"titles"];
  }
  return cell;
}

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 if(tableview.tag == 1)
  {
      //code for email  
        NSLog(@"email==%@",[[yourarrayName objectAtIndex:indexPath.row]objectForKey:@"email"]);

  }

  else if(tableview.tag == 2)
  {
      //code for phone

    NSLog(@"phone==%@",[[yourarrayName objectAtIndex:indexPath.row]objectForKey:@"phone"]);

  }

  else if(tableview.tag == 3)
  {

         NSLog(@"title==%@",[[yourarrayName objectAtIndex:indexPath.row]objectForKey:@"titles"]);
  }

}