Swift에서 CollectionView로 광고판 슬라이딩 효과

클래스 만들기:PlayCollectionViewController.swift

//cell 
private let reuseIdentifier = "reuseIdentifier"
class PlayCollectionViewController: UICollectionViewController {

    // 
    private let pageCount = 6
    // ( )
    private var layout: UICollectionViewFlowLayout = PlayLayout()

    init() {
        super.init(collectionViewLayout: layout)
    }

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

    override func viewDidLoad() {
        super.viewDidLoad()

        // cell
        collectionView?.registerClass(NewfearureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    //MARK: - UICollectionDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pageCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewfearureCell
        cell.imageIndex = indexPath.item
        return cell
    }
}

CollectionView의 cell 사용자 정의

//MARK: -  (PlayCollectionViewController.swift ) collectionViewCell
class NewfearureCell: UICollectionViewCell {

    // 
    private var imageIndex:Int? {
        didSet {
            // ( )
            iconView.image = UIImage(named: "image_\(imageIndex!)")
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

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

    private func setupUI() {

        // contentView
        contentView.addSubview(iconView)
        // ( )
        iconView.xmg_Fill(contentView)
    }

    //MARK:  
    private lazy var iconView = UIImageView()
}

UICollectionViewFlowLayout 상속, 사용자 정의 레이아웃

private class PlayLayout: UICollectionViewFlowLayout {

    // 
    override func prepareLayout() {

        // layout 
        itemSize = UIScreen.mainScreen().bounds.size
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal

        // 
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.bounces = false
        collectionView?.pagingEnabled = true
    }
}

좋은 웹페이지 즐겨찾기