카테고리 없음

swift 콜렉션 뷰 셀 만들기

kingarthur 2024. 9. 14. 00:18

오랜만에 만들다 보니...헤메기 일수 ~~ 

익숙하지 않은 콜렉션뷰 만들기. 

 

차근차근 만들어보자 

import UIKit

class HorizontalCell: UICollectionViewCell {
    static let identifier = "HorizontalCell"

    // 셀 안에 들어갈 이미지와 라벨
    let imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.translatesAutoresizingMaskIntoConstraints = false
        return imageView
    }()
    
    let titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        label.tintColor = .black
        label.numberOfLines = 1
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    let subtitleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 12, weight: .light)
        label.textColor = .lightGray
        label.numberOfLines = 1
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.layer.cornerRadius = 10 // 코너 레디어스 설정
        contentView.clipsToBounds = true
        contentView.backgroundColor = .white
        
        contentView.addSubview(imageView)
        contentView.addSubview(titleLabel)
        contentView.addSubview(subtitleLabel)
        
        
        // 오토레이아웃 설정
        NSLayoutConstraint.activate([
            imageView.topAnchor.constraint(equalTo: contentView.topAnchor),
            imageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
            imageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
            imageView.heightAnchor.constraint(equalTo: contentView.heightAnchor, multiplier: 0.7),
            
            titleLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 8),
            titleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 5),
            titleLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -5),
            
            subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 8),
            subtitleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 5),
            subtitleLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -5),
            
        ])
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

먼저 셀에 들어갈 내용을 만들어준다 ~~~~ 

여기서 셀의 내용 모양을 잡아준다고 생각하면된다. 

 

import UIKit

class HorizontalCollectionView: UICollectionView, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
    
    let items: [String]
    let subitems: [String]
    let images: [UIImage]
    
    init(items: [String], subitems: [String], images: [UIImage]) {
        self.items = items
        self.subitems = subitems
        self.images = images
        
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        super.init(frame: .zero, collectionViewLayout: layout)
        
        self.delegate = self
        self.dataSource = self
        self.showsHorizontalScrollIndicator = false
        self.register(HorizontalCell.self, forCellWithReuseIdentifier: HorizontalCell.identifier)
        
        self.translatesAutoresizingMaskIntoConstraints = false
        self.backgroundColor = .black
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HorizontalCell.identifier, for: indexPath) as! HorizontalCell
        cell.titleLabel.text = items[indexPath.row]
        cell.subtitleLabel.text = subitems[indexPath.row]
        cell.imageView.image = images[indexPath.row] // 이미지 설정
        return cell
    }
    
    // 셀 크기 설정
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 150, height: 200) // 예시 셀 크기
    }
    
    // 셀 사이의 간격 설정
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10 // 세로 간격
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 10 // 가로 간격
    }

}

여기서 셀의 간격들을 정해주고 백그라운드를 정해준다 ~~  여기서 셀의 크기도 지정해준다. 

셀의 정보창을 가져온다고 생각하면 될듯 ~ 

 

import UIKit


class HomeView: UIView {
    
    let scrollView = UIScrollView()
    let stackView = UIStackView()
    
    let popularWorkoutLabel: UILabel = {
        let workoutLabel = UILabel()
        workoutLabel.text = "Popular workout"
        workoutLabel.textColor = .white
        workoutLabel.textAlignment = .left
        workoutLabel.font = .boldSystemFont(ofSize: 20)
        workoutLabel.translatesAutoresizingMaskIntoConstraints = false
        return workoutLabel
    }()
    
    let crossFitLabel: UILabel = {
        let workoutLabel = UILabel()
        workoutLabel.text = "CrossFit WOD"
        workoutLabel.textColor = .white
        workoutLabel.textAlignment = .left
        workoutLabel.font = .boldSystemFont(ofSize: 20)
        workoutLabel.translatesAutoresizingMaskIntoConstraints = false
        return workoutLabel
    }()
    
    override init(frame: CGRect) {
        super .init(frame: frame)
        setUpView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setUpView() {
        
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(scrollView)
        
        NSLayoutConstraint.activate([
            scrollView.topAnchor.constraint(equalTo: topAnchor),
            scrollView.bottomAnchor.constraint(equalTo: bottomAnchor),
            scrollView.leadingAnchor.constraint(equalTo: leadingAnchor),
            scrollView.trailingAnchor.constraint(equalTo: trailingAnchor)
        ])
        
        // StackView 설정
        stackView.axis = .vertical
        stackView.spacing = 20
        stackView.translatesAutoresizingMaskIntoConstraints = false
        scrollView.addSubview(stackView)
        
        NSLayoutConstraint.activate([
            stackView.topAnchor.constraint(equalTo: scrollView.topAnchor),
            stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
            stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
            stackView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
        ])
        
        // 가로 스크롤 컬렉션 뷰 추가
        let horizontalCollectionView1 = HorizontalCollectionView(
            items: ["5분", "3min ", "1min "],
            subitems: ["안녕하세요", "안녕", "누구세요"],
            images: [
                UIImage(named: "workout1") ?? UIImage(),
                UIImage(named: "workout2") ?? UIImage(),
                UIImage(named: "workout3") ?? UIImage(),
            ]
        )
        
        let horizontalCollectionView2 = HorizontalCollectionView(
            items: ["New Item 1", "New Item 2", "New Item 3", "New Item 4"],
            subitems: ["새 설명 1", "새 설명 2", "새 설명 3", "새 설명 4"],
            images: [
                UIImage(named: "newImage1") ?? UIImage(),
                UIImage(named: "newImage2") ?? UIImage(),
                UIImage(named: "newImage3") ?? UIImage(),
                UIImage(named: "newImage4") ?? UIImage(),
            ]
        )
        
        stackView.addArrangedSubview(popularWorkoutLabel)
        stackView.addArrangedSubview(horizontalCollectionView1)
        stackView.addArrangedSubview(crossFitLabel)
        stackView.addArrangedSubview(horizontalCollectionView2)
        
        NSLayoutConstraint.activate([
            // 높이 설정
            popularWorkoutLabel.heightAnchor.constraint(equalToConstant: 30),
            horizontalCollectionView1.heightAnchor.constraint(equalToConstant: 200),
            crossFitLabel.heightAnchor.constraint(equalToConstant: 30),
            horizontalCollectionView2.heightAnchor.constraint(equalToConstant: 200),
            
        ])
        
    }

}

이렇게 하면 첫번째 두번째에 틀을 만들어 논거라 ~ 

세번째에 내용만 바꺼가면서 계속 셀들을 복제가 가능하다 ~

까먹지말고 사용하자.. 자주 사용하는거니.

미자막에 당근 뷰이니 컨트롤러에는 연결시켜줘야겠지 그건 간단하니 패스 ~