菜鸟教程小白 发表于 2022-12-11 20:01:10

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


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

<pre><code>NSDateFormatter *formatter = [ init];
initWithLocaleIdentifier:@&#34;en_US&#34;]];
//    ;
;
NSDate *headerDate = (NSDate *);
NSString *headerTitle = ;
</code></pre>

<p>代码如下:</p>

<pre><code>- (void)viewDidLoad {
    ;

    ;

    NSURL *serverURL = ;
    [ loadData:serverURL withCompletion:^(NSArray *itemListArray, NSError *error) {
      if (error != nil) {
            UIAlertView *errorAlertView = [ initWithTitle:@&#34;Server Error&#34; message:@&#34;Unable to fetch Data from Server&#34; delegate:nil cancelButtonTitle:@&#34;Ok&#34; otherButtonTitles:nil, nil];
            ;
      }
      else {
            fetchData = ;
            ;
      }
    }];
    ;}


- (NSMutableDictionary *)convertSectionTableData:(NSArray *)convertDataSet keyString:(NSString *)keyString {
    NSMutableDictionary *outputData = ;
    NSMutableArray *temp = ;
    NSString *key = NULL;
    for (NSDictionary *dic in convertDataSet) {

      if (key == NULL) {
            key = ;
      } else if (key != ) {
            ;
            temp = ;

            key = ;
      }

      if ([ isEqualToString: key]) {
            ;
      }

      if (dic == ) {
            ;
      }
    }

    return outputData;}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return ;}

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

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @&#34;CustomListTableCell&#34;;

    CustomListTableCell *cell = (CustomListTableCell *);

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

    NSDictionary *data = [ objectAtIndex:row];

    cell.homeLabel.text = ;

    return cell;}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return ;}

@end
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>基本思想是字典是无序的,因此您需要某种方法以正确的顺序检索它们。我可能会建议构建字典键的排序数组。</p>

<pre><code>// build dictionary of objects, keyed by date

NSMutableDictionary *objectsForDates = ...

// build sorted array of dates in descending order

NSArray *dates = [ sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
    return ;
}];
</code></pre>

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

<pre><code>- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return ] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return ];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = ;
    Location *object = self.objectsForDates];
    cell.textLabel.text = object.home;
    return cell;
}
</code></pre>

<hr/>

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

<ol>
<li><p>我建议对 JSON 的内容使用自定义对象类型。这提供了比简单的 <code>NSDictionary</code> 更强的类型。</p>

<p>我还要确保类型更自然地键入(例如,<code>id</code> 看起来应该是 <code>NSInteger</code>;<code>date</code> 看起来应该是 <code>NSDate</code>)。</p>

<p>我还要给这个自定义类型一个 <code>initWithDictionary</code> 初始化器,以简化解析代码。</p></li>
<li><p>构建以日期为键的字典的逻辑(您的 <code>convertSectionTableData</code>)可以简化一点。</p></li>
<li><p>您的 UI 日期格式化程序不应使用 <code>en_US</code> 的 <code>locale</code>。解析 JSON 的格式化程序应该(或者更准确地说,它应该使用 <code>en_US_POSIX</code>),但是在 UI 中呈现格式时,应该使用用户自己的语言环境。</p>

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

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

<pre><code>@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 = ;
    if (self) {
      self.identifier = integerValue];
      self.home = dictionary[@&#34;home&#34;];
      ];
    }
    return self;
}

- (void)setDateFromString:(NSString *)string {
    static NSDateFormatter *formatter;
    static dispatch_once_t onceToken;
    dispatch_once(&amp;onceToken, ^{
      formatter = [ init];
      formatter.locale = ;
      formatter.timeZone = ;
      formatter.dateFormat = @&#34;yyyy-MM-dd&#34;;
    });

    self.date = ;
}
@end
</code></pre>

<p>和</p>

<pre><code>@interface ViewController ()

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

@property (nonatomic, strong) NSDateFormatter *formatter;

@end

@implementation ViewController

- (void)viewDidLoad {
    ;

    // set formatter for output

    self.formatter = [ init];
    ]];
    self.formatter.timeZone = ;

    // perform request

    NSURL *url = ;
    [[ dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
      if (error || !data) {
            NSLog(@&#34;networkError: %@&#34;, error);
            return;
      }

      NSError *parseError;
      NSArray *values = ;
      if (!]) {
            NSLog(@&#34;parseError: %@&#34;, parseError);
      }

      // build dictionary of objects, keyed by date

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

      // build sorted array of dates in descending order

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

      // now update UI

      dispatch_async(dispatch_get_main_queue(), ^{
            self.objectsForDates = objectsForDates;
            self.dates = dates;
            ;
      });

    }] resume];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return ] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return ];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = ;
    Location *object = self.objectsForDates];
    cell.textLabel.text = object.home;
    return cell;
}

@end
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 如何在 TitleForHeaderInSection 上对日期进行排序,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/44877601/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/44877601/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 如何在 TitleForHeaderInSection 上对日期进行排序