2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CHTCollectionViewWaterfallLayout でセルの横幅取得

Last updated at Posted at 2016-06-16

Pinterest風のCollectionViewを利用できるようにする
CHTCollectionViewWaterfallLayout
で、セルの横幅を取りたかったのでメモ

UICollectionViewLayout を拡張して実装

import Foundation
import CHTCollectionViewWaterfallLayout

extension UICollectionViewLayout {
    func getCHTItemWidth() -> CGFloat{
        guard let collectionViewRect = self.collectionView?.bounds else {
            return 0
        }
        if self is CHTCollectionViewWaterfallLayout {
            let me = self as! CHTCollectionViewWaterfallLayout
            let columnWidth = collectionViewRect.width - (me.sectionInset.left + me.sectionInset.right)
            return ( columnWidth - CGFloat(me.columnCount - 1) * me.minimumColumnSpacing ) / me.columnCount
        } else {
            return collectionViewRect.width
        }
    }
}

使用方法

横幅:セルの横幅 縦幅:セルの横幅+60 のセルを返したい時

extension ViewController : CHTCollectionViewDelegateWaterfallLayout {
    func collectionView(collectionView: UICollectionView!,
                        layout collectionViewLayout: UICollectionViewLayout!,
                               sizeForItemAtIndexPath indexPath: NSIndexPath!) -> CGSize {
        let w = collectionViewLayout.getCHTItemWidth()
        return CGSize(width: w, height: w + 60)
    }
}

セルの横幅に合わせた柔軟なレイアウトが組めて楽しいです

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?