【问题标题】:Organizing UITableViewCell's by Creation Date按创建日期组织 UITableViewCell
【发布时间】:2013-12-17 15:26:41
【问题描述】:

我在两个单独的 NSDictionaries 中有推文和 instagram 图片,目前我只是通过将所有其他帖子设为推文来聚合帖子,而后者则是 Instagram 图片。我将如何使用这两个并组织所有UITableViewCell 并按日期组织它们?

我在想我会从每个返回 created_at 值并将字符串转换为 NSDate,但是我将如何为每条推文和 instapic 执行此操作?

【问题讨论】:

    标签: ios objective-c uitableview twitter instagram


    【解决方案1】:

    出于您的目的,您必须创建一个新数组,将推文和 instaPics 数组合并为一个数组,然后将所有数据排序为单个数组。

    合并两个数据数组如下::

    NSArray *pictureArray = [tweets arrayByAddingObjectsFromArray: instaPics];
    

    注意 :: NSDictionary (NSMutableDictionary) 默认情况下根据其键值排序。这里我们根据包含字典的特定键对数组进行排序

    现在将您的 pictureArray 排序如下::

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"created_at" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    pictureArray = [pictureArray sortedArrayUsingDescriptors:sortDescriptors];    
    

    然后将您的 tableview 方法重新定义为 ::

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *tweetsCellIdentifier = @"tweetsCell";
        static NSString *instaCellIdentifier = @"instaCell";
        UITableViewCell *cell = nil;
        BOOL tweets = NO;
    
        // Now you get dictionary that may be of tweets array or instagram array 
        // Due to its different structure
        // I thinks your both dictionaries have different structure
        NSDictionary *pictDictionary = pictureArray[indexPath.row];
        if (your_check_condition for tweets dictionary) {
            tweets = YES;
        }
    
        // Get cell according to your dictionary data that may be from tweets or instagram
        if (tweets) {
           cell = [tableView dequeueReusableCellWithIdentifier:tweetsCellIdentifier];
        } else {
           cell = [tableView dequeueReusableCellWithIdentifier:instaCellIdentifier];
        }
    
        if (cell == nil) {
          // Design your cell as you desired;
          if (tweets) {
            // Design cell for tweets
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tweetsCellIdentifier];
          } else {
            // Design cell for instagram
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:instaCellIdentifier];
          }
    
        }
    
    
         // Write your login to get dictionary picture data
         // Tweets and Instagram array are merged. So get appropriate data with your logic
         // May be both dictionaries structure are different. so write your logic to get picture data
          // Fill data according tweets dict or instgram
          // Get cell elements in which you will show dict data i.e. images, title etc.
          if (tweets) {
            // Fill cell data for tweets
          } else {
            // Fill cell data for instagram
          }
    
          return cell;
    }
    

    在得到图片数组中的数据后重新加载你的tableview如下..

    //Reload TableView
    [tableView reloadData];
    

    也许对你有帮助。

    已编辑 :: 如下编辑您的代码。我修改了您的 instgram 单元格创建和填充。像这样定义您的推文单元格设计和为 instagram 完成的填充数据

    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        static NSString *tweetsCellIdentifier = @"tweetsCell";
        static NSString *instaCellIdentifier = @"instaCell";
        UITableViewCell *cell = nil;
        BOOL tweets = YES;
        BOOL twitterLoggedIn = [user boolForKey:@"twitterLoggedIn"];
    
    // Now you get dictionary that may be of tweets array or instagram array
    // Due to its different structure
    // I thinks your both dictionaries have different structure
    NSDictionary *totalFeedDictionary = totalFeed[indexPath.row];
    
    // Get cell according to your dictionary data that may be from tweets or instagram
    if (tweets) {
        cell = [tableView dequeueReusableCellWithIdentifier:tweetsCellIdentifier];
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:instaCellIdentifier];
    }
    
    if (cell == nil) {
        // Design your cell as you desired;
        if (tweets) {
            // Now correct it as instagram cell design below your tweets cell design
            // Only create here desired elements and its define design pattern here
            // Don't Fill here At last already we fill it 
            // Due to scrolling cells are reuse and must be fill all time when they come from deque cel
            // Design cell for tweets
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tweetsCellIdentifier];
    
            cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Background.png"]];
    
            NSDictionary *tweet = totalFeed[indexPath.row];
    
            //Set username for twitter
            NSString *name = [[tweet objectForKey:@"user"] objectForKey:@"name"];
            UILabel *twitterNameLabel = (UILabel *)[cell viewWithTag:202];
            [twitterNameLabel setFont:[UIFont fontWithName:@"Helvetica-Light" size:12.0]];
            [twitterNameLabel setText:name];
    
    
            //Set status for twitter
            NSString *text = [tweet objectForKey:@"text"];
            UILabel *twitterTweetLabel = (UILabel *)[cell viewWithTag:203];
            [twitterTweetLabel setFont:[UIFont fontWithName:@"Helvetica-Light" size:10.0]];
            [twitterTweetLabel setText:text];
    
    
            //Set Profile Pic for twitter
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSString *imageUrl = [[tweet objectForKey:@"user"] objectForKey:@"profile_image_url"];
                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
    
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIImageView *profilePic = (UIImageView *)[cell viewWithTag:201];
                    profilePic.image = [UIImage imageWithData:data];
    
                    //Make the Profile Pic ImageView Circular
                    CALayer *imageLayer = profilePic.layer;
                    [imageLayer setCornerRadius:25];
                    [imageLayer setMasksToBounds:YES];
                });
            });
    
    
            //Set number of Favorites for Tweet
            NSString *favoritesCount = [[tweet objectForKey:@"user"]objectForKey:@"favourites_count"];
            UIButton *favoritesButton = (UIButton *)[cell viewWithTag:204];
            [favoritesButton setTitle:[NSString stringWithFormat:@"  %@",favoritesCount] forState:UIControlStateNormal];
            [favoritesButton setTitle:[NSString stringWithFormat:@"  %@",favoritesCount] forState:UIControlStateHighlighted];
            favoritesButton.titleLabel.font = [UIFont fontWithName:@"Helvetica-Light" size:12];
    
        } else {
            // Design cell for instagram
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:instaCellIdentifier];
    
            cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Background.png"]];
    
            UIImageView *instagramImageView = [[UIImageView alloc] init];
            instagramImageView.tag = 104;
             [cell.contentView addSubview:instagramImageView];
    
            UILabel *instagramUserLabel = [[UILabel alloc] init];
            instagramUserLabel.tag = 102;
            [instagramUserLabel setFont:[UIFont fontWithName:@"Helvetica-Light" size:16.0]];
            [cell.contentView addSubview:instagramUserLabel];
    
            UILabel *instagramCaptionLabel = [[UILabel alloc] init];
                [instagramCaptionLabel setFont:[UIFont fontWithName:@"Helvetica-Light" size:12.0]];
            instagramCaptionLabel.tag = 103;
             [cell.contentView addSubview:instagramCaptionLabel];
    
            UIImageView *instagramProfilePic = [[UIImageView alloc] init];
            instagramProfilePic.frame = CGRectMake(35, 31, 50, 50);
            instagramProfilePic.tag = 101;
    
            [cell.contentView addSubview:instagramProfilePic];
        }
    
    }
    
    // Fill Data here
    if (tweets) {
         // Now correct as below your tweets cell filling
         // Only get here desired elements and fill them here
    } else {
         NSDictionary *entry = totalFeed[indexPath.row];
    
         NSString *imageUrlString = entry[@"images"][@"low_resolution"][@"url"];
         NSURL *url = [NSURL URLWithString:imageUrlString];
            UIImageView *instagramImageView = (UIImageView *)[cell viewWithTag:104];
            [instagramImageView setImageWithURL:url];
    
            NSString *user =  entry[@"user"][@"full_name"];
            UILabel *instagramUserLabel = (UILabel *)[cell viewWithTag:102];
            [instagramUserLabel setText:user];
    
         UILabel *instagramCaptionLabel = (UILabel *)[cell viewWithTag:103];
         if (entry[@"caption"] != [NSNull null] && entry[@"caption"][@"text"] != [NSNull null])            {
                NSString *caption = entry[@"caption"][@"text"];
                [instagramCaptionLabel setText:caption];
            }else{
                NSString *caption = @"";
                [instagramCaptionLabel setText:caption];
    
            }
    
         NSString *imageUserPicUrl = entry[@"user"][@"profile_pic"][@"url"];
         NSURL *profileURL = [NSURL URLWithString:imageUserPicUrl];
         UIImageView *instagramProfilePic = (UIImageView *)[cell viewWithTag:101];
         [instagramProfilePic setImageWithURL:profileURL];
    }
    
    return cell;
    

    【讨论】:

    • 但是我有两种不同类型的单元格,一种用于 Twitter 单元格,一种用于 Instagram 单元格,我该如何订购这两种单元格?
    • @prnk28 看到这个编辑过的答案。如果您有任何问题,请发表评论。等待!!!
    • @Nour1991 我已经输入了所有数据,而我的 uitableview 现在什么也没有显示并且崩溃了。我已经编辑了这个问题以展示我是如何做到的。这是错误:CRASH : UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:
    • @prnk28 在你的if(tweets) 中你设置了两次单元格值,在你说cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tweetsCellIdentifier]; 你说:cell = [tableView dequeueReusableCellWithIdentifier:tweetsCellIdentifier]; 所以删除第二行,看看它是怎么回事!因为您收到的错误表明您的单元格返回为零,这弄乱了UITableView
    • 它仍然给我同样的问题
    【解决方案2】:

    在调用 cellForRowAtIndexPath 之前,您必须使用 creation_datetweetsinstaPics 数组进行排序。在 viewDidLoad 中写下这段代码,然后重新加载 tableView。

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"created_at" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    tweets = [tweets sortedArrayUsingDescriptors:sortDescriptors];
    instaPics = [instaPics sortedArrayUsingDescriptors:sortDescriptors];
    //Reload TableView
    [tableView reloadData];
    

    希望这会有所帮助:)

    【讨论】:

    • 好吧,我使用的两个数组都是 NSMutableDictionaries,所以该方法不起作用,而且在我对数组进行排序后,我会在 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 方法的开头做什么。如何替换顶部的 if()else() 语句?
    • 对 [tableView reloadData] 的调用将在订购字典后重新加载表格。字典不可排序。但是,您可以通过为 dictionary.allKeys 或 dictionary.allValues 中的键/值创建数组来对字典的键或值进行排序,然后对字典进行排序和重新填充。
    • @prnk28 Chris 的评论绝对正确,您需要对字典键进行排序,然后使用它们来创建这样的 tableView 单元格。 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //...你的代码...// NSDictionary *tweet = tweets[tweets.allKeys[indexPath.row]]; //...您的代码...// } 关于您的 if()else() 语句,我不明白您到底想做什么。请清除
    【解决方案3】:
    [self.tweets sortUsingComparator:^(Tweet *a, Tweet *b){
        return [b.dateCreated compare:a.dateCreated];
    }];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      相关资源
      最近更新 更多