UIKit에서 리스트와 그리드를 구현하는 방법에는 UICollectionView와 UITableView 두가지가 있다.
그 중, UICollectionView를 이용하는 방법을 알아보자!
⭐️ UICollectionView를 이용해서 리스트 및 그리드를 개발할때 핵심 3가지 ⭐️
✔️ Data
: 어떤 데이터 쓸지
✔️ Presentation
: 셀을 어떻게 표현할건지
✔️ Layout
: 셀들의 레이아웃을 어떻게 할건지
상위 Class: UIViewController
Class명: StockRankViewController
방금 만든 class 명을 복사해놓고,
Identity Insepctor에 들어간 후,
AutoLayout은 부모 View와 연결하여
Leading, Top, Trailing, Bottom Space to Safe Area를 모두 0으로 설정하였다.
👇🏻 연결 결과
Data, Presentation, Layout 을 알려줄 누군가가 필요하다..!
아래 코드를 viewDidLoad() 메소드 안에 작성한다.
(*delegate: 프로토콜의 일종)
// Data, Presentation 을 알려줌
collectionView.dataSource = self
// Layout 을 알려줌
collectionView.delegate = self
상위 Class: UICollectionViewCell
Class명: StockRankCollectionViewCell
2번 과정과 마찬가지로 Main Storyboard와 연결해 준다.
① 업데이트 되어야 하는 ui component 연결
② ui compenent에 데이터 업데이트
extension StockRankViewController: UICollectionViewDataSource {
// 섹션에 넣을 아이템의 개수
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return stockList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 재사용 가능한 셀을 가져옴 (indexPath 번째)
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "StockRankCollectionViewCell", for: indexPath) as? StockRankCollectionViewCell else {
// casting 실패 시
return UICollectionViewCell()
}
let stock = stockList[indexPath.item]
// indexPath 안에는 섹션에 대한 정보, 섹션에 들어가는 데이터 정보 등이 있다
cell.configure(stock)
return cell
}
}
extension StockRankViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// collectionView width와 동일하게 설정
return CGSize(width: collectionView.bounds.width, height: 80)
}
}
StockRankCollectionViewCell에
convertToCurrencyFormat라는 메소드를 추가하고, configure 메소드에 적용하였다.
func configure(_ stock: StockModel) {
rankLabel.text = "\(stock.rank)"
companyIconImageView.image = UIImage(named: stock.imageName)
companyNameLabel.text = stock.name
companyPriceLabel.text = "\(convertToCurrencyFormat(price: stock.price)) 원"
diffLabel.text = "\(stock.diff) %"
}
func convertToCurrencyFormat(price: Int) -> String {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.maximumFractionDigits = 0 // 소수점 몇째자리까지 보여줄지
let result = numberFormatter.string(from: NSNumber(value: price))!
return result
}
StockRankCollectionViewCell의
configure 메소드에 아래 코드를 추가하면,
등가폭이 +일때는 빨간색 글씨, -일때는 파란색 글씨로 표현할 수 있다.
diffLabel.textColor = stock.diff > 0 ? UIColor.systemRed : UIColor.systemBlue