티스토리 뷰

iOS

iOS) UICollectionView cell 왼쪽정렬

hyun99999 2021. 7. 21. 21:08
728x90
반응형

UICollectionView cell 왼쪽정렬

1.다음과 같은 스위프트 파일을 만듭니다.

import Foundation
import UIKit

class LeftAlignedCollectionViewFlowLayout: UICollectionViewFlowLayout {

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let attributes = super.layoutAttributesForElements(in: rect)

        var leftMargin = sectionInset.left
        var maxY: CGFloat = -1.0
        attributes?.forEach { layoutAttribute in
            if layoutAttribute.frame.origin.y >= maxY {
                leftMargin = sectionInset.left
            }

            layoutAttribute.frame.origin.x = leftMargin

            leftMargin += layoutAttribute.frame.width + minimumInteritemSpacing
            maxY = max(layoutAttribute.frame.maxY , maxY)
        }

        return attributes
    }
}

2.storyboard 에서 Collection View Flow Layout 의 클래스로 위의 클래스를 지정해준다.

완성

적용하게되면 오른쪽 뷰처럼 왼쪽 정렬이 된다.

728x90
반응형

'iOS' 카테고리의 다른 글

iOS) UITableView 당겨서 새로고침  (0) 2021.07.21
iOS) Core Data  (0) 2021.07.21
iOS) delegate 에 여러개의 컬렉션뷰를 연결하기  (0) 2021.07.21
iOS) UIButton programmatically  (0) 2021.07.21
iOS) convert UIColor to String  (0) 2021.07.21
댓글
최근에 올라온 글
최근에 달린 댓글
글 보관함
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
링크
Total
Today
Yesterday