Rodhos Soft

備忘録を兼ねた技術的なメモです。Rofhos SoftではiOSアプリ開発を中心としてAndroid, Webサービス等の開発を承っております。まずはご相談下さい。

UICorrectionView、スペース調整

UICollectionViewFlowLayoutを継承し、layoutAttributesForElementsInRectをoverrideする。
superのlayoutAttributesForElementsInRectでattributeが帰ってくるのでその個々のframeを調整すれば良い。

具体的には

    override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        
        
        
        
        
        // この領域の属性群を取得
        let answer = super.layoutAttributesForElementsInRect(rect)
        
        // 属性を順にループさせて調整をする。
        for (var i=1; i<answer!.count; i = i + 1)
        {
            // 元属性
            let currentLayoutAttributes = answer![i]
            
            // 手前の属性
            let prevLayoutAttributes = answer![i-1]
            
            // スペースの最大値を0に
            let maximumSpacing = 0.0 as CGFloat;
            
            // 手前の属性の一番右側の座標をoriginにする
            let origin = CGRectGetMaxX(prevLayoutAttributes.frame)
            
            // そこからスペーシングをおいて現属性の幅をたしたものが、コレンテンツサイズ内であることを条件に
            if (origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize().width) {
                
                // 現属性の左端をその右端+スペーシングに設定する。
                var frame = currentLayoutAttributes.frame
                frame.origin.x = origin + maximumSpacing;
                currentLayoutAttributes.frame = frame
            }
            

        }

以下を参照した。
ios - Cell spacing in UICollectionView - Stack Overflow