Skip to content

Instantly share code, notes, and snippets.

@uruly
Created June 10, 2018 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uruly/6fafc9cba1728846f07714612b5d1338 to your computer and use it in GitHub Desktop.
Save uruly/6fafc9cba1728846f07714612b5d1338 to your computer and use it in GitHub Desktop.
CarouselView - Horizontal CollectionView
//
// CarouselCell.swift
// CardCarousel2
//
// Created by Reona Kubo on 2018/06/11.
// Copyright © 2018年 Reona Kubo. All rights reserved.
//
import UIKit
class CarouselCell: UICollectionViewCell {
}
//
// CarouselView.swift
// CardCarousel2
//
// Created by Reona Kubo on 2018/06/11.
// Copyright © 2018年 Reona Kubo. All rights reserved.
//
import UIKit
class CarouselView: UICollectionView {
let cellIdentifier = "carousel"
let pageCount = 5
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
self.delegate = self
self.dataSource = self
self.register(CarouselCell.self, forCellWithReuseIdentifier: cellIdentifier)
}
convenience init(frame: CGRect) {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 200, height: frame.height / 2)
layout.scrollDirection = .horizontal
self.init(frame: frame, collectionViewLayout: layout)
// 水平方向のスクロールバーを非表示にする
self.showsHorizontalScrollIndicator = false
self.backgroundColor = UIColor.white
}
}
extension CarouselView: UICollectionViewDelegate {
}
extension CarouselView: UICollectionViewDataSource {
// セクションごとのセル数
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.pageCount
}
// セルの設定
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath)
cell.contentView.backgroundColor = UIColor.green
return cell
}
}
//
// ViewController.swift
// CardCarousel2
//
// Created by Reona Kubo on 2018/06/11.
// Copyright © 2018年 Reona Kubo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var carouselView:CarouselView!
override func viewDidLoad() {
super.viewDidLoad()
let width = self.view.frame.width
let height = self.view.frame.height
carouselView = CarouselView(frame: CGRect(x:0, y:0, width:width, height:height))
carouselView.center = CGPoint(x:width / 2,y: height / 2)
self.view.addSubview(carouselView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment