📌 여섯번째 프로젝트 (2)
Insta Search View 앱의 홈 탭을 꾸며보자!
1️⃣ Component AutoLayout
2️⃣ "NewsViewController" 이름의 UIViewController 만들기
// NewsViewController.swift
import UIKit
class NewsViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
if let flowlayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowlayout.estimatedItemSize = .zero
}
}
}
extension NewsViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 24
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NewsCell", for: indexPath) as? NewsCell else {
return UICollectionViewCell()
}
let imageName = "animal\(indexPath.item + 1)"
cell.configure(imageName)
return cell
}
}
extension NewsViewController: UICollectionViewDelegateFlowLayout {
// cell 사이즈 조절
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.bounds.width
let height = width * 3/4 + 60
return CGSize(width: width, height: height)
}
// item 위아래 간격
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
}
3️⃣ "NewsCell" 이름의 UICollectionViewCell 만들기
// NewsCell.swift
import UIKit
class NewsCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
// cell 재사용을 준비하는 함수
override func prepareForReuse() {
super.prepareForReuse()
// 재사용될 때는 기존의 이미지를 일단 없애주기 = reset!
imageView.image = nil
}
// cell 세팅
func configure(_ imageName: String){
imageView.image = UIImage(named: imageName)
}
}
🚫 imageView의 Content Mode를 Aspect Fill로 해주어야 커스텀한 imageView의 비율에 맞게 이미지가 가득차게 보인다!
🚀 구현 완료!
Reference
패스트캠퍼스 온라인 강의
'iOS > Toy project' 카테고리의 다른 글
[iOS : Toy Project] Diffable DataSource, Compositional Layout을 이용해 프로젝트 개선하기 (0) | 2022.06.04 |
---|---|
[iOS : Toy Project] NRC Onboarding (0) | 2022.05.31 |
[iOS : Toy Project] Insta Search View (1) (0) | 2022.05.29 |
[iOS : Toy Project] Apple Framework List (2) (0) | 2022.05.28 |
[iOS : Toy Project] Apple Framework List (1) (0) | 2022.05.28 |