2014-12-14 7 views
0

Я работаю над UICollectionView и UICollectionViewFlowLayout, и моей целью приложений является изменение размера изображения в макетах между малым размером и большим размером и размещение UILable в макете размера большого размера и удаление в малом размере используя кнопку.CellForItemAtIndexPath не отвечает на UICollectionVieLayout

Я могу успешно изменить размер макетов изображений, но у меня есть 1 проблема и 2 вопроса в этом сценарии.

Задача 1:

CellForItemAtIndexPath не вызывается каждый раз, я попытался с помощью reloadData но говорят мгновенных снимков вид, что не было вынесено результаты в пустой снимок. убедитесь, что ваш вид был , сделанный как минимум один раз перед снимком. Как пройти эту проблему и вызвать этот метод.

Вопрос 1:

Как можно отобразить UILabel в большом зрений и снять в небольших зрениях

Вопрос 2:

Если я нахожусь в 4-е строки Большого макета изображения и перейти к небольшому виду макет изображения и вернуться к макету большого вида. Как я могу отобразить одно и то же изображение 4-го ряда в макете большого представления, вместо того, чтобы показывать снова обновленный экран.

Пожалуйста, найти код для вашей ссылки ниже:

{//View Controller 

#import <UIKit/UIKit.h> 

@interface ViewController : UICollectionViewController<UICollectionViewDataSource, UICollectionViewDelegate> 
-(void)animationDidChange:(id)sender; 
@end 


#import "ViewController.h" 
#import "CollectionViewCell.h" 
#import "SingleView.h" 
#import "GridView.h" 

@interface ViewController() 
@property (nonatomic, strong) SingleView *largeLayout; 
@property (nonatomic, strong) GridView *smallLayout; 
@property (nonatomic, strong) NSArray *images; 
@property(nonatomic, strong)UIButton * button; 


@end 

static NSString *ItemIdentifier = @"ItemIdentifier"; 

@implementation ViewController 

-(void)loadView 
{ 


    self.smallLayout = [[GridView alloc] init]; 
    self.largeLayout = [[SingleView alloc] init]; 

    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.largeLayout]; 
    [self.collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:ItemIdentifier]; 

    self.collectionView.delegate = self; 
    self.collectionView.dataSource = self; 
    self.collectionView.backgroundColor=[UIColor whiteColor]; 
    self.collectionView.bounces = YES; 
    self.collectionView.alwaysBounceVertical = YES; 
    self.collectionView.indicatorStyle = UIScrollViewIndicatorStyleWhite; 
    self.automaticallyAdjustsScrollViewInsets=YES; 
} 


- (void)viewDidLoad { 

    UIToolbar *toolbar = [[UIToolbar alloc] init]; 
    toolbar.frame = CGRectMake(0, 18, self.view.frame.size.width, 44); 
    toolbar.barTintColor=[UIColor whiteColor]; 

    //Added Label to toolbar for title 
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 23)]; 
    label2.textAlignment = NSTextAlignmentLeft; 
    label2.backgroundColor = [UIColor clearColor]; 
    label2.textColor = [UIColor grayColor]; 
    label2.text = @"Title"; 
    label2.font = [UIFont systemFontOfSize:14.0]; 
    UIBarButtonItem *toolBarTitle = [[UIBarButtonItem alloc] initWithCustomView:label2]; 
    UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace 
                      target:nil action:nil]; 
    //Added button to the toolbar 
    _button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    [_button addTarget:self 
       action:@selector(animationDidChange:) 
    forControlEvents:UIControlEventTouchUpInside]; 
    [_button setBackgroundImage:[UIImage imageNamed:@"on"] forState:UIControlStateNormal]; 
    _button.backgroundColor=[UIColor clearColor]; 
    _button.frame = CGRectMake(150.0, 210.0, 40.0, 40.0); 
    UIBarButtonItem *toolBarButton = [[UIBarButtonItem alloc] initWithCustomView:_button]; 
    NSArray *items = [[NSArray alloc] initWithObjects: toolBarTitle,spacer,toolBarButton, nil]; 
    [toolbar setItems:items]; 
    self.navigationItem.titleView = toolbar; 

    [super viewDidLoad]; 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

#pragma mark - User Interface Methods 

-(void)animationDidChange:(id)sender 
{ 
    CollectionViewCell * cell= [[CollectionViewCell alloc]init]; 
    if (self.collectionView.collectionViewLayout == self.smallLayout) 
    { 
[_button setBackgroundImage:[UIImage imageNamed:@"on"] forState:UIControlStateNormal]; 
     [self.largeLayout invalidateLayout]; 
     [self.collectionView reloadData]; 
     [self.collectionView setCollectionViewLayout:self.largeLayout animated:YES]; 

    } 
    else if(self.collectionView.collectionViewLayout == self.largeLayout) 
    { 
[_button setBackgroundImage:[UIImage imageNamed:@"off"] forState:UIControlStateNormal]; 
     [self.smallLayout invalidateLayout]; 

     [self.collectionView setCollectionViewLayout:self.smallLayout animated:YES]; 
    } 
} 

#pragma mark - UICollectionView DataSource & Delegate methods 

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

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 
{ 
    return 11; 
} 
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CollectionViewCell *cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:ItemIdentifier forIndexPath:indexPath]; 

    [cell setImage:[UIImage imageNamed:[NSString stringWithFormat:@"groupA_%ld.jpg", indexPath.row ]]]; 

     return cell; 



} 


@end 


//COllectionViewCell 

#import <UIKit/UIKit.h> 

@interface CollectionViewCell : UICollectionViewCell 
@property(nonatomic, strong) UILabel * dateString; 
@property(nonatomic, strong)UILabel* nameString; 
@property(nonatomic, strong)NSString* layout; 
-(void)setImage:(UIImage *)image; 
-(void)setLabel; 
-(void)removeLabel; 
@end 


#import "CollectionViewCell.h" 
@interface CollectionViewCell() 

@property (nonatomic, strong) UIImageView *imageView; 


@end 
@implementation CollectionViewCell 
@synthesize dateString,nameString,layout; 
- (id)initWithFrame:(CGRect)frame 
{ 

    if (!(self = [super initWithFrame:frame])) return nil; 

    self.imageView = [[UIImageView alloc] initWithFrame:CGRectInset(CGRectMake(0, 0, CGRectGetWidth(frame), CGRectGetHeight(frame)), 0, 0)]; 

    self.imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 
    self.imageView.contentMode = UIViewContentModeScaleAspectFit; 

    if ([self.layout isEqualToString: @"small"]) { 
     NSLog(@"Hello"); 
    } 
    self.dateString =[[UILabel alloc]initWithFrame:CGRectMake(0, 270, 350, 20)]; 
    self.nameString =[[UILabel alloc]initWithFrame:CGRectMake(0, 290, 350, 20)]; 


    [self.contentView addSubview:self.imageView]; 
    [self.contentView addSubview:self.dateString]; 
    [self.contentView addSubview:self.nameString]; 
    self.backgroundColor = [UIColor whiteColor]; 

    return self; 
} 



-(void)setImage:(UIImage *)image 
{ 

    self.imageView.image = image; 
} 

-(void)setLabel{ 

self.dateString.text [email protected]"Hello"; 

} 
-(void)removeLabel{ 
    [self.dateString removeFromSuperview]; 
} 

@end 


//CollectionView layout Large 

@interface SingleView : UICollectionViewFlowLayout 

@end 

#import "SingleView.h" 

@implementation SingleView 
-(id)init 
{ 
    if (!(self = [super init])) return nil; 

    self.itemSize = CGSizeMake(350, 300); 
    self.sectionInset = UIEdgeInsetsMake(10, 0, 10, 0); 
    self.minimumInteritemSpacing = 10.0f; 
    self.minimumLineSpacing = 10.0f; 


    return self; 
} 
@end 

//CollectionViewLayout Small 


#import <UIKit/UIKit.h> 

@interface GridView : UICollectionViewFlowLayout 

@end 


#import "GridView.h" 

@implementation GridView 
-(id)init 
{ 
    if (!(self = [super init])) return nil; 

    self.itemSize = CGSizeMake(130, 130); 
    self.sectionInset = UIEdgeInsetsMake(10, 40, 10, 40); 
    self.minimumInteritemSpacing = 10.0f; 
    self.minimumLineSpacing = 10.0f; 
    return self; 
} 

@end 

} 

ответ

0

К сожалению, у меня нет прямого ответа на вашу проблему. У меня было нечто подобное, когда я изменить размер мой взгляд на вращение устройства, и он пошел прочь, перемещая методы в 'viewDidLayoutSubviews`

-(void)viewDidLayoutSubviews 
{ 
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; 
    if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight){ 
     [self landscapeUISetup]; 

    } else if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) { 
     [self portraitUISetup]; 
     NSLog(@"portrait"); 

    } 

} 

На вопрос 1, я предлагаю попробовать простой скрытие ярлыка при загрузке маленький вид. Так что-то вроде

self.label.hidden = YES; 

И когда вы меняете обратно в большой

self.label.hidden = NO; 

На вопрос 2: Вы должны сохранить индекс видимой ячейки, а затем вызвать метод Scrolling

[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO]; 
+0

Какой размер, по вашему мнению, создает проблему ширины или высоты? – Kumar

+0

Я думаю, что проблема в том, что вид изменен в неправильном месте. Просто попробуйте внести изменения в 'viewDidLayoutSubview' и посмотреть, не исчезла ли ошибка. Сообщение об ошибке также может быть ошибкой в ​​iOS 8. Вы можете видеть много сообщений, если вы ищете это сообщение. – Pahnev

Смежные вопросы