需要使用分段控制来显示表格的方法吗?

时间:2010-01-16 17:03:04

标签: iphone objective-c uitableview

您好我在视图上使用分段控件。在这个分段控件的帮助下,我想在我的视图中显示不同的表格,假设我的表格中有两个段,点击段1,我想显示表格1,点击段2,我想显示表2我的表1是普通表,表2是分组表,Apple正在使用方法在应用程序商店中显示不同类别的不同应用程序,但我不知道该怎么做。请建议任何方法或任何相同的代码示例也将适用。

由于 桑迪

2 个答案:

答案 0 :(得分:26)

我们通过使用单个tableview,然后在每个tableview回调方法中执行if / case语句来返回基于在分段控件中选择的值的正确数据。

首先,将segmentedControl添加到titleView,并在更改时设置回调函数:

- (void) addSegmentedControl {
    NSArray * segmentItems = [NSArray arrayWithObjects: @"One", @"Two", nil];
    segmentedControl = [[[UISegmentedControl alloc] initWithItems: segmentItems] retain];
    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
    segmentedControl.selectedSegmentIndex = 0;
    [segmentedControl addTarget: self action: @selector(onSegmentedControlChanged:) forControlEvents: UIControlEventValueChanged];
    self.navigationItem.titleView = segmentedControl;
}

接下来,当更改分段控件时,您需要加载新段的数据,并重置表视图以显示此数据:

- (void) onSegmentedControlChanged:(UISegmentedControl *) sender {
    // lazy load data for a segment choice (write this based on your data)
    [self loadSegmentData:segmentedControl.selectedSegmentIndex];

    // reload data based on the new index
    [self.tableView reloadData];

    // reset the scrolling to the top of the table view
    if ([self tableView:self.tableView numberOfRowsInSection:0] > 0) {
        NSIndexPath *topIndexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
        [self.tableView scrollToRowAtIndexPath:topIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
}

然后在你的tableView回调中,你需要有每段的逻辑值来返回正确的东西。我将向您展示一个回调作为示例,但实现其余的如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"GenericCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"GenericCell" owner:self options:nil] objectAtIndex: 0];
    }   

    if (segmentedControl.selectedSegmentIndex == 0) { 
        cell.textLabel.text = @"One";
    } else if (segmentedControl.selectedSegmentIndex == 1) {
        cell.textLabel.text = @"Two";
    }
    return cell;
}

就是这样,希望它有所帮助。

答案 1 :(得分:3)

另一个选择是拥有一个容器视图,您可以将tableView当前作为子视图添加到其中。您甚至可以通过创建表视图控制器然后添加.view作为容器的子视图,将每个表放在不同的视图控制器中以保持分离,但如果这样做,则必须手动调用{{ 1}}和viewWillAppear(当你触摸分段控件时交换表时,你只是调用它们并不是很难)。