iOS/Toy project

[iOS : Toy Project] Insta Search View (2)

yevdev 2022. 5. 29. 18:12

📌 여섯번째 프로젝트 (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

패스트캠퍼스 온라인 강의