gpt4 book ai didi

iphone - 需要使用分段控件显示表格的方法吗?

转载 作者:太空狗 更新时间:2023-10-30 03:23:05 25 4
gpt4 key购买 nike

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

谢谢桑迪

最佳答案

我们通过拥有一个 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;
}

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

- (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;
}

就这些吧,希望对你有帮助。

关于iphone - 需要使用分段控件显示表格的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2078200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com