카테고리 없음

[iOS] 프로그래밍 방식으로 ViewController + CollectionView 생성 및 ScrollView에 추가

행복을전해요 2021. 1. 21. 13:11

대리자 메서드를 올바르게 추가하고 있는지 확인하십시오.

@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    UICollectionView *_collectionView;
    }
    
    - (void)viewDidLoad {
        UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
            _collectionView=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
                [_collectionView setDataSource:self];
                    [_collectionView setDelegate:self];
                    
                        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
                            [_collectionView setBackgroundColor:[UIColor redColor]];
                            
                                [self.view addSubview:_collectionView];
                                
                                    [super viewDidLoad];
                                        // Do any additional setup after loading the view, typically from a nib.
                                        }
                                        
                                        - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
                                            return 10;
                                            }
                                            
                                            - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
                                                UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
                                                
                                                    cell.backgroundColor=[UIColor blueColor];
                                                        return cell;
                                                        }
                                                        
                                                        - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
                                                        {
                                                            return CGSizeMake(40, 40);
                                                            }
                                                            


출처
https://stackoverflow.com/questions/22009779