[ios] 프로그래밍 방식으로 UICollectionView 만들기

코드 만 사용하여 간단한 UICollectionView를 설정하는 방법을 보여줄 가이드 또는 자습서를 찾고 있습니다.

나는 통해 넘어 가고있어 애플의 사이트에있는 문서 , 내가 사용하고 참조 매뉴얼을 뿐만 아니라.

그러나 스토리 보드 또는 XIB / NIB 파일을 사용하지 않고 UICollectionView를 설정하는 방법을 보여줄 수있는 간단한 안내서의 이점을 얻을 수 있지만 불행히도 검색 할 때 스토리 보드가있는 자습서 만 찾을 수 있습니다.



답변

헤더 파일 :-

@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    UICollectionView *_collectionView;
}

구현 파일 :-

- (void)viewDidLoad
{
     [super viewDidLoad];
     self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

     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];


    // Do any additional setup after loading the view, typically from a nib.
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 15;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    cell.backgroundColor=[UIColor greenColor];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(50, 50);
}

산출—

여기에 이미지 설명을 입력하십시오


답변

swift4 사용자의 경우 :-

class TwoViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.cyan
        self.view.addSubview(collectionView)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
       var cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)

       cell.backgroundColor = UIColor.green
       return cell
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        return CGSize(width: 50, height: 50)
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
    }
}


답변

스위프트 2.0

다음을 그리는 데 필요한 메소드를 구현하는 대신 CollectionViewCells:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
    {
        return CGSizeMake(50, 50);
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets
    {
        return UIEdgeInsetsMake(5, 5, 5, 5); //top,left,bottom,right
    }

사용하다 UICollectionViewFlowLayout

func createCollectionView() {
    let flowLayout = UICollectionViewFlowLayout()

    // Now setup the flowLayout required for drawing the cells
    let space = 5.0 as CGFloat

    // Set view cell size
    flowLayout.itemSize = CGSizeMake(50, 50)

    // Set left and right margins
    flowLayout.minimumInteritemSpacing = space

    // Set top and bottom margins
    flowLayout.minimumLineSpacing = space

    // Finally create the CollectionView
    let collectionView = UICollectionView(frame: CGRectMake(10, 10, 300, 400), collectionViewLayout: flowLayout)

    // Then setup delegates, background color etc.
    collectionView?.dataSource = self
    collectionView?.delegate = self
    collectionView?.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellID")
    collectionView?.backgroundColor = UIColor.whiteColor()
    self.view.addSubview(collectionView!)
}

그런 다음 필요에 따라 UICollectionViewDataSource메소드를 구현하십시오 .

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20;
    }
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    var cell:UICollectionViewCell=collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath) as UICollectionViewCell;
    cell.backgroundColor = UIColor.greenColor();
    return cell;
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}


답변

스위프트 3

class TwoViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let flowLayout = UICollectionViewFlowLayout()

        let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.cyan

        self.view.addSubview(collectionView)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return 20
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)

        cell.backgroundColor = UIColor.green
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        return CGSize(width: 50, height: 50)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
    {
        return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
    }

}


답변

  1. @Warewolf의 답변을 바탕으로 다음 단계는 사용자 정의 셀을 만드는 것입니다.

    File -> New -> File -> User Interface -> Empty -> Call이 펜촉으로 이동 하십시오 "customNib".

  2. 당신에 customNib드래그 UICollectionView세포.이 세포 식별자를 다시 부여 @"Cell".

  3. File -> New -> File -> Cocoa Touch Class -> Class명명 된 "CustomCollectionViewCell"서브 클래스 if UICollectionViewCell.

  4. 사용자 정의 펜촉으로 돌아가서 셀을 클릭하고이 사용자 정의 클래스를 "CustomCollectionViewCell"만듭니다.

  5. viewDidLoad viewcontroller대신에

    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];

    있다

    UINib *nib = [UINib nibWithNibName:@"customNib" bundle:nil];
    [_collectionView registerNib:nib forCellWithReuseIdentifier:@"Cell"];

  6. 또한 새 셀 식별자로 변경하십시오.

    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];


답변

UIcollection view에서 사용자 정의 셀을 처리 할 수 ​​있습니다 (아래 코드 참조).여기에 이미지 설명을 입력하십시오

- (void)viewDidLoad
{
  UINib *nib2 = [UINib nibWithNibName:@"YourCustomCell" bundle:nil];
    [CollectionVW registerNib:nib2 forCellWithReuseIdentifier:@"YourCustomCell"];


    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setItemSize:CGSizeMake(200, 230)];
    flowLayout.minimumInteritemSpacing = 0;
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    [CollectionVW setCollectionViewLayout:flowLayout];

    [CollectionVW reloadData];
}

#pragma mark - COLLECTIONVIEW
#pragma mark Collection View CODE

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

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return Array.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"YourCustomCell";
    YourCustomCell *cell = (YourCustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

    cell.MainIMG.image=[UIImage imageNamed:[Array objectAtIndex:indexPath.row]];


    return cell;
}

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

#pragma mark Collection view layout things
// Layout: Set cell size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize mElementSize;
    mElementSize=CGSizeMake(kScreenWidth/3.4, 150);
    return mElementSize;
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 5.0;
}

// Layout: Set Edges
- (UIEdgeInsets)collectionView: (UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (isIphone5 || isiPhone4)
    {
        return UIEdgeInsetsMake(15,15,5,15);  // top, left, bottom, right
    }
    else if (isIphone6)
    {
        return UIEdgeInsetsMake(15,15,5,15);  // top, left, bottom, right
    }
    else if (isIphone6P)
    {
        return UIEdgeInsetsMake(15,15,5,15);  // top, left, bottom, right
    }

    return UIEdgeInsetsMake(15,15,5,15);  // top, left, bottom, right
}


답변

Apple Docs :

- (id)initWithFrame:(CGRect)frame
      collectionViewLayout:(UICollectionViewLayout *)layoutParameters

프로그래밍 방식으로 컬렉션 뷰 객체를 초기화 할 때이 방법을 사용하십시오. 레이아웃 매개 변수에 nil을 지정하면 콜렉션보기를 화면에 표시하기 전에 레이아웃 오브젝트를 collectionViewLayout 특성에 지정해야합니다. 그렇지 않으면 컬렉션보기에서 화면에 항목을 표시 할 수 없습니다.

이 메소드는 지정된 초기화 프로그램입니다.

이 메소드는를 초기화하는 데 사용됩니다 UICollectionView. 여기서 당신은 프레임과 UICollectionViewLayout객체 를 제공 합니다.

UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];

마지막에 추가 UICollectionViewA와 subview보기에.

이제 컬렉션보기가 문법적으로 추가되었습니다. 계속 학습 할 수 있습니다.
행복한 학습 !! 그것이 당신을 돕기를 바랍니다.