2014-01-29 29 views
0

我有一個TableView。它使用JSON從網絡接收數據並將數據填充到單元格中。另外,我在TableView上面有SegmentedControl。我必須瞭解如何通過單擊segmentedControl的每個段顯示不同的數據(通過'type'參數)。通過使用UISegmentedControl拆分UITableView中的數據

一切工作正常(我的代碼如下)。但我想通過使用於數據拆分到每個段中的數據數組 '類型' 參數

我的JSON代碼:

[{ 
    "title":"message one", 
    "subtitle":"sub one", 
    "type":1 
},{ 
    "title":"message two", 
    "subtitle":"sub two", 
    "type":2 
}, { 
    "title":"message three", 
    "subtitle":"sub three", 
    "type":2 
}, { 
    "title":"message four", 
    "subtitle":"sub four", 
    "type":3 
}] 

SegmentedControl:

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"All", @"Present", @"Missing", nil]]; 
    [segmentedControl addTarget:self action:@selector(segmentedControlChanged:) forControlEvents:(UIControlEventValueChanged)]; 
    segmentedControl.frame = CGRectMake(0, 0, 100, 30); 
    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; 
    segmentedControl.selectedSegmentIndex = 0; 
    [self.tableView addSubview:segmentedControl]; 

segmentedControlChanged方法

- (void) segmentedControlChanged:(id)sender 
    { 
     UISegmentedControl* segmentedControl = (UISegmentedControl*)sender; 
     segmentIndex = segmentedControl.selectedSegmentIndex; // segmentIndex defined in .h file 
     [self.tableView reloadData]; 
    } 

讓我們來看一些細胞

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; 

    if(cell == nil){ 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"]; 
    } 

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 

    UILabel *titleField = (UILabel *)[cell viewWithTag:10]; 
    UILabel *subField = (UILabel *)[cell viewWithTag:11]; 

    titleField.text = [NSString stringWithFormat:@"%@", [[dataList objectAtIndex:indexPath.row] valueForKey:@"title"]]; 
    subField.text = [NSString stringWithFormat:@"%@", [[dataList objectAtIndex:indexPath.row] valueForKey:@"subtitle"]]; 

    switch (segmentIndex) 
    { 
     case 0: 
      cell.backgroundColor = [UIColor brownColor]; 
      break; 
     case 1: 
      cell.backgroundColor = [UIColor whiteColor]; 
      break; 
     case 2: 
      cell.backgroundColor = [UIColor blueColor]; 
      break; 
     default: 
      break; 
    } 

    return cell; 
} 

謝謝你,對不起我的英文!

回答

2

創建第二個屬性,它保存當前選定選項卡的過濾對象,然後將所有表視圖方法設置爲從該數組中取出。

財產申報:

@property (strong, nonatomic) NSArray *filteredObjects; 

在你segmentControlChanged:方法:

self.filteredObjects = [self.dataList filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"type == %d", segmentedControl.selectedSegmentIndex]]; 
+0

非常感謝您!很棒!但最後你忘了一個squire括號,我把這個代碼放到單一方法中。它將防止第一次數據加載時出錯並通過拉動重新加載。再次感謝你! –