添加更多单元格 UICollectionView

Posted

技术标签:

【中文标题】添加更多单元格 UICollectionView【英文标题】:Add more cells UICollectionView 【发布时间】:2013-07-26 18:55:14 【问题描述】:

现在我正在通过进入屏幕底部而不是添加新单元格来替换 Instagram 中的图像。如何添加新单元格而不是替换以前的单元格?

这是我检索下一页图像的总实现文件:

@interface StreamViewController () <UITextFieldDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) NSMutableDictionary *timelineResponse;
@property (nonatomic, strong) CredentialStore *credentialStore;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@end

@implementation StreamViewController

- (void)viewDidLoad 
    [super viewDidLoad];

    [self refreshInstagram];

    //Refresh
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl addTarget:self action:@selector(startRefresh:)
             forControlEvents:UIControlEventValueChanged];
    [self.collectionView addSubview:refreshControl];

    //Instigate Navigation Bar Buttons
    UIButton *barButton = [UIButton buttonWithType:UIButtonTypeCustom];

    [barButton setTitle:@"" forState:UIControlStateNormal];
    [barButton setBackgroundImage:[UIImage imageNamed:@"barButton.png"] forState:UIControlStateNormal];
    [barButton setBackgroundImage:[UIImage imageNamed:@"barButton_s.png"] forState:UIControlStateHighlighted];
    [barButton addTarget:self action:@selector(didTapBarButton:) forControlEvents:UIControlEventTouchUpInside];
    barButton.frame = CGRectMake(0.0f, 0.0f, 30.0f, 30.0f);
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:barButton];

    self.navBar.leftBarButtonItem = barButtonItem;

    UIButton *postButton = [UIButton buttonWithType:UIButtonTypeCustom];

    [postButton setTitle:@"" forState:UIControlStateNormal];
    [postButton setBackgroundImage:[UIImage imageNamed:@"pen_usIMG.png"] forState:UIControlStateNormal];
    [postButton setBackgroundImage:[UIImage imageNamed:@"pen_sIMG.png"] forState:UIControlStateHighlighted];
    [postButton addTarget:self action:@selector(didTapPostButton:) forControlEvents:UIControlEventTouchUpInside];
    postButton.frame = CGRectMake(0.0f, 0.0f, 30.0f, 30.0f);
    UIBarButtonItem *postButtonItem = [[UIBarButtonItem alloc] initWithCustomView:postButton];

    self.navBar.rightBarButtonItem = postButtonItem;

    //Reload by default
    [self.collectionView reloadData];




//Global refresh Instagram Method
- (void)refreshInstagram 

    [[InstagramClient sharedClient] getPath:@"users/self/feed"
                                 parameters:nil
                                    success:^(AFHTTPRequestOperation *operation, id responseObject) 
                                        NSLog(@"Response: %@", responseObject);
                                        self.timelineResponse = responseObject;
                                        [self.collectionView reloadData];

                                     failure:^(AFHTTPRequestOperation *operation, NSError *error) 
                                        NSLog(@"Failure: %@", error);
                                    ];



- (void)nextInstagramPage:(NSIndexPath *)indexPath
    NSDictionary *page = self.timelineResponse[@"pagination"];
    NSString *nextPage = page[@"next_url"];

    [[InstagramClient sharedClient] getPath:[NSString stringWithFormat:@"%@",nextPage] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) 
        [self.collectionView cellForItemAtIndexPath:indexPath];
        self.timelineResponse = [responseObject mutableCopy];
        [self.timelineResponse addEntriesFromDictionary:responseObject];
        [self.collectionView reloadData];
     failure:^(AFHTTPRequestOperation *operation, NSError *error) 
        NSLog(@"Failure: %@", error);
    ];




- (NSMutableArray *)entries 
    return self.timelineResponse[@"data"];


- (NSArray *)pages 
    return self.timelineResponse[@"pagination"];



- (NSURL *)imageUrlForEntryAtIndexPath:(NSIndexPath *)indexPath 
    NSDictionary *entry = [self entries][indexPath.row];
    NSString *imageUrlString = entry[@"images"][@"standard_resolution"][@"url"];
    return [NSURL URLWithString:imageUrlString];


#pragma mark - UICollectionViewDelegate

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath 
    //int y = arc4random() % 200+50;


    return CGSizeMake(150, 150);



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

    RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:@"Item Tapped!" message:@"Thank God its working"];
    [modal show];



- (void)scrollViewDidScroll:(UIScrollView *)scrollView

    if (scrollView.contentOffset.y == roundf(scrollView.contentSize.height-scrollView.frame.size.height)) 
        NSLog(@"we are at the endddd");
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

        [self.collectionView performBatchUpdates:^
            [self nextInstagramPage:indexPath];

         completion:^(BOOL finished) 


        
         ];
    


#pragma mark - UICollectionViewDataSource

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 

    return [[self entries] count];



-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 

    if ( indexPath.item == ([[self entries] count] - 1) ) 
        // download more data and add it to the 'entries' array
        [self refreshInstagram];


    

    ImageCell *cell = (ImageCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"imageCell"
                                                                             forIndexPath:indexPath];
    NSURL *url = [self imageUrlForEntryAtIndexPath:indexPath];
    NSLog(@"%@", url);
    [cell.imageView setImageWithURL:url];
    cell.backgroundColor = [UIColor whiteColor];

    return cell;


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView 
    return 1;


#pragma mark - NavigationBarButtons

- (void)didTapBarButton:(id)sender 

    [self.sidePanelController showLeftPanelAnimated:YES];



- (void)startRefresh:(UIRefreshControl *)sender 
    [self refreshInstagram];
    [sender endRefreshing];



-(void)didTapPostButton:(id)sender 




@end

这是一种添加新单元格的方法:

-(void)addNewCells 
    [self.collectionView performBatchUpdates:^
        int resultsSize = [[self entries]count];
        [self.results addObjectsFromArray:newData];
        NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];
        for (int i = resultsSize; i < resultsSize + newData.count; i++)
            [arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
    
     [self.collectionView insertItemsAtIndexPaths:arrayWithIndexPaths];
     
                                  completion:nil];

【问题讨论】:

你试过更新collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section的返回值吗?并且(相应地)将更多图像添加到您保存图像的数组(或任何容器)中? 我把它设为数组中的图像数量 据我所知,如果当用户滚动到底部时,您会抓取更多图像并将它们添加到您的数组中(以便它现在具有较旧和较新的图像),然后调用 @987654324 @(并且 numberOfItemsInSection 现在返回 [yourArray count]),它应该做你想做的事。 我应该把reloadData放在哪里 【参考方案1】:

您必须保留从服务返回的照片的数组。正如 Mundi 的回答所暗示的那样,字典将不起作用,因为 添加 字典中的响应将 替换 现有的键/值对。这就是为什么你看到闪烁。

NSMutableArray 属性添加到您的视图控制器,并将数据中的条目添加到其中。

[self.photosArray addObjectsFromArray:responseObject[@"data"]];

然后在您的 entries 方法中使用用户 self.photosArray

【讨论】:

感谢大家的帮助【参考方案2】:

您只需增加您的数据数组。将timelineResponse 变成NSMutableArray

[self.timelineResponse addObjectsFromArray:responseObject];

[self.timelineResponse addEntriesFromDictionary:responseObject];
[self.collectionView reloadData]; 

【讨论】:

当前 timelineResponse 是一个 NSDictionary 我可以做同样的事情而不将其更改为 nsmutable 数组。我在上面添加了整个 .m 文件以供参考 好吧,你明白了:) 等待我不明白是我还是我没有将它从字典更改为数组 无论你使用什么,让它可变。在您的声明中,它是一个NSDictionary,所以将它变成NSMutableDictionary 并使用addEntriesFromDictionary 来扩展它。 我收到此错误:2013-07-27 11:42:57.141 Floadt[4877:c07] *** 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:'-[__NSCFDictionary的setObject:forKey:]:突变方法发送到不可变对象” ***第一掷调用堆栈:(0x2fc5012 0x25f6e7e 0x2fc4deb 0x2f8b347 0x2faaa9b 0x60e46 0x36049 0x276953f 0x277b014 0x276b7d5 0x2f6baf5 0x2f6af44 0x2f6ae1b 0x2ba27e3 0x2ba2668 0x1763ffc 0x2d6d 0x2c95)的libc ++ abi.dylib:终止称为抛出异常(lldb)

以上是关于添加更多单元格 UICollectionView的主要内容,如果未能解决你的问题,请参考以下文章

CollectionView 添加额外的单元格“添加更多”

UITableView 仅加载在设备上可见的自定义单元格,并在添加更多单元格时崩溃

如何将数据复制到单元格中,制作表格并向其中添加更多数据

UITextView 底部有更多文字和更多空白

UITableViewCell,两个单元格都获得了附件视图

iOS动态地将新单元格加载到表格视图的底部