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

san*_*ndy 11 iphone objective-c uitableview

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

谢谢桑迪

And*_*icz 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;
}
Run Code Online (Sandbox Code Playgroud)

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

- (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];
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的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;
}
Run Code Online (Sandbox Code Playgroud)

这就是它,希望它有所帮助.