UICollectionView display 3 items per row

后端 未结 7 590
离开以前
离开以前 2020-12-16 03:30

I have a UICollectionView created from storyboard,

I want to have 3 items per row in the view. I managed to do that using the following:

    - (CGSiz         


        
7条回答
  •  青春惊慌失措
    2020-12-16 04:05

    You need to calculate first the available space for the content and then divide that by the number of items you want to present per row.

    Here is an example assuming that the UICollectionView is taking all the width of the screen

    private let numberOfItemPerRow = 2
    
    private let screenWidth = UIScreen.main.bounds.width
    private let sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    private let minimumInteritemSpacing = CGFloat(10)
    private let minimumLineSpacing = CGFloat(10)
    
    // Calculate the item size based on the configuration above  
    private var itemSize: CGSize {
        let interitemSpacesCount = numberOfItemPerRow - 1
        let interitemSpacingPerRow = minimumInteritemSpacing * CGFloat(interitemSpacesCount)
        let rowContentWidth = screenWidth - sectionInset.right - sectionInset.left - interitemSpacingPerRow
    
        let width = rowContentWidth / CGFloat(numberOfItemPerRow)
        let height = width // feel free to change the height to whatever you want 
    
        return CGSize(width: width, height: height)
    }
    

提交回复
热议问题