티스토리 뷰

IOS

UICollectionView 적용하기 (Swift 4.2)

하악생 2019. 5. 22. 16:51

UICollectionView는 사진 앱처럼 하나의 Row에 여러개 아이템을 보여줄 수 있는 UI이다.

 

처음에는 이 UI가 있는 줄 모르고

UITableView에 아이템마다 UIStackView로 구성하여 크기를 맞춰주는 방법을 계속 고민했었다. (그러면 엄청 복잡할텐데)

 

아무튼 이 뷰는 Cell의 가로 길이에 따라 Column 개수와 Row 개수가 정해지며

사용 방법은 UITableView와 유사하다. 

 

1. 스토리 보드에서 빈 컨트롤러에 UICollectionView를 추가한다. 

2.  UICollectionViewCell에 dentifier를 지정한다.  ("TestCollectionCell"라고 지었다.)

identifier 등록
식별할 수 있도록 Cell 색상 변경

3. TestCollectionViewController.swift를 생성하고, 스토리보드 뷰와 연결할 뷰를 선언하고

// TestCollectionViewContoller.swift

class TestCollectionViewController : UIViewController
	
	...

    @IBOutlet weak var collectionView : UICollectionView!

	...
}

컨트롤러에 TestCollectionViewController 적용 후 뷰를 연결해준다.

4. UICollectionView를 사용하기 위한 Delegate, DataSource를 등록한다.

// TestCollectionViewController.swift

class TestCollectionViewController : UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet weak var collectionView : UICollectionView!

    override func viewDidLoad() {
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.reloadData()

    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 32	// 32개의 아이템을 보여준다.
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TestCollectionCell", for: indexPath) // TestCollectionCell은 스토리보드에서 등록한 Cell Identifier

        return cell
    }
}

5. 결과 ( Cell 크기는 50 * 50 ( 기본크기 ) )

 

 

반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함