• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 如何在 TitleForHeaderInSection 上对日期进行排序

[复制链接]
菜鸟教程小白 发表于 2022-12-11 20:01:10 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我的程序如下:..- 但是,我想在 TitleForHeaderInSection 中按日期降序对数据进行排序,并且还想将 Header 中的日期格式化为

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier"en_US"]];
//    [formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setDateFormat"EEE, d MMM yyyy"];
NSDate *headerDate = (NSDate *)[managedObject valueForKey"dateCreated"];
NSString *headerTitle = [formatter stringFromDate:headerDate];

代码如下:

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.navigationItem setTitle"List of Items"];

    NSURL *serverURL = [NSURL URLWithString:SERVER_URL];
    [[DataManager sharedInstance] loadData:serverURL withCompletion:^(NSArray *itemListArray, NSError *error) {
        if (error != nil) {
            UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle"Server Error" message"Unable to fetch Data from Server" delegate:nil cancelButtonTitle"Ok" otherButtonTitles:nil, nil];
            [errorAlertView show];
        }
        else {
            fetchData = [self convertSectionTableData:itemListArray keyString"date"];
            [self.listTableView reloadData];
        }
    }];
    [self.listTableView reloadData];}


- (NSMutableDictionary *)convertSectionTableDataNSArray *)convertDataSet keyStringNSString *)keyString {
    NSMutableDictionary *outputData = [NSMutableDictionary dictionary];
    NSMutableArray *temp = [NSMutableArray array];
    NSString *key = NULL;
    for (NSDictionary *dic in convertDataSet) {

        if (key == NULL) {
            key = [dic objectForKey:keyString];
        } else if (key != [dic objectForKey:keyString]) {
            [outputData setValue:temp forKey:key];
            temp = [NSMutableArray array];

            key = [dic objectForKey:keyString];
        }

        if ([[dic objectForKey:keyString] isEqualToString: key]) {
            [temp addObject:dic];
        }

        if (dic == [convertDataSet lastObject]) {
            [outputData setValue:temp forKey:key];
        }
    }

    return outputData;}

- (NSInteger)numberOfSectionsInTableViewUITableView *)tableView {
    return [fetchData count];}

-(NSInteger)tableViewUITableView *)tableView numberOfRowsInSectionNSInteger)section {
    return [[fetchData allValues][section] count];}

-(UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"CustomListTableCell";

    CustomListTableCell *cell = (CustomListTableCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    int section = (int)indexPath.section;
    int row = (int)indexPath.row;

    NSDictionary *data = [[fetchData allValues][section] objectAtIndex:row];

    cell.homeLabel.text = [data objectForKey"home"];

    return cell;}

- (NSString *)tableViewUITableView *)tableView titleForHeaderInSectionNSInteger)section {
    return [fetchData allKeys][section];}

@end



Best Answer-推荐答案


基本思想是字典是无序的,因此您需要某种方法以正确的顺序检索它们。我可能会建议构建字典键的排序数组。

// build dictionary of objects, keyed by date

NSMutableDictionary *objectsForDates = ...

// build sorted array of dates in descending order

NSArray *dates = [[objectsForDates allKeys] sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
    return [obj2 comparebj1];
}];

然后您可以使用此 dates 对象来表示表格 View 的“部分”,然后使用它来知道要返回字典中的哪个条目:

- (NSInteger)numberOfSectionsInTableViewUITableView *)tableView {
    return [self.dates count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.objectsForDates[self.dates[section]] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [self.formatter stringFromDate:self.dates[section]];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier"Cell" forIndexPath:indexPath];
    Location *object = self.objectsForDates[self.dates[indexPath.section]][indexPath.row];
    cell.textLabel.text = object.home;
    return cell;
}

注意,我建议对您的代码进行一些不相关的更改:

  1. 我建议对 JSON 的内容使用自定义对象类型。这提供了比简单的 NSDictionary 更强的类型。

    我还要确保类型更自然地键入(例如,id 看起来应该是 NSIntegerdate 看起来应该是 NSDate)。

    我还要给这个自定义类型一个 initWithDictionary 初始化器,以简化解析代码。

  2. 构建以日期为键的字典的逻辑(您的 convertSectionTableData)可以简化一点。

  3. 您的 UI 日期格式化程序不应使用 en_USlocale。解析 JSON 的格式化程序应该(或者更准确地说,它应该使用 en_US_POSIX),但是在 UI 中呈现格式时,应该使用用户自己的语言环境。

    您的 UI 日期格式化程序也不应该使用固定的 dateFormat 字符串。使用预先存在的 dateStyle 之一,或者如果您必须使用 dateFormat,则使用 dateFormatFromTemplate 构建本地化版本。

不管怎样,把它们放在一起,你会得到类似的东西:

@interface Location : NSObject
@property (nonatomic) NSInteger identifier;
@property (nonatomic, copy) NSString *home;
@property (nonatomic, strong) NSDate *date;

- (instancetype)initWithDictionary:(NSDictionary *)dictionary;
@end

@implementation Location

- (instancetype)initWithDictionary:(NSDictionary *)dictionary {
    self = [super init];
    if (self) {
        self.identifier = [dictionary[@"id"] integerValue];
        self.home = dictionary[@"home"];
        [self setDateFromString:dictionary[@"date"]];
    }
    return self;
}

- (void)setDateFromString:(NSString *)string {
    static NSDateFormatter *formatter;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        formatter = [[NSDateFormatter alloc] init];
        formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
        formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
        formatter.dateFormat = @"yyyy-MM-dd";
    });

    self.date = [formatter dateFromString:string];
}
@end

@interface ViewController ()

@property (nonatomic, strong) NSMutableDictionary *objectsForDates;
@property (nonatomic, strong) NSArray *dates;

@property (nonatomic, strong) NSDateFormatter *formatter;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // set formatter for output

    self.formatter = [[NSDateFormatter alloc] init];
    [self.formatter setDateFormat:[NSDateFormatter dateFormatFromTemplate:@"EEEdMMMyyyy" options:0 locale:[NSLocale currentLocale]]];
    self.formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

    // perform request

    NSURL *url = [NSURL URLWithString:@"http://borindatabase.000webhostapp.com/jsonData.php"];
    [[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error || !data) {
            NSLog(@"networkError: %@", error);
            return;
        }

        NSError *parseError;
        NSArray *values = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
        if (![values isKindOfClass:[NSArray class]]) {
            NSLog(@"parseError: %@", parseError);
        }

        // build dictionary of objects, keyed by date

        NSMutableDictionary *objectsForDates = [[NSMutableDictionary alloc] init];
        for (NSDictionary *value in values) {
            Location *object = [[Location alloc] initWithDictionary:value];
            NSMutableArray *objects = objectsForDates[object.date];
            if (!objects) {
                objects = [[NSMutableArray alloc] init];
                objectsForDates[object.date] = objects;
            }
            [objects addObjectbject];
        }

        // build sorted array of dates in descending order

        NSArray *dates = [[objectsForDates allKeys] sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
            return [obj2 comparebj1];
        }];

        // now update UI

        dispatch_async(dispatch_get_main_queue(), ^{
            self.objectsForDates = objectsForDates;
            self.dates = dates;
            [self.tableView reloadData];
        });

    }] resume];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.dates count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.objectsForDates[self.dates[section]] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [self.formatter stringFromDate:self.dates[section]];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    Location *object = self.objectsForDates[self.dates[indexPath.section]][indexPath.row];
    cell.textLabel.text = object.home;
    return cell;
}

@end

关于ios - 如何在 TitleForHeaderInSection 上对日期进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44877601/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap