셀 간격과 UICollectionView - UICollectionViewFlowLayout 크기 비율을 설정하는 방법
추가하려고 합니다.UICollectionView
로.ViewController
셀 사이에 공백이 없는 '한 줄에 3개의 셀'이 필요합니다(그리드 모양이어야 합니다).셀 폭은 화면 크기의 3분의 1이어야 합니다.layout.item
너비는 같아야 합니다.하지만 난 이걸 알았어.
이 크기를 줄이면(7~8픽셀 등) 더 좋지만, 세 번째 행의 셀은 완전히 보이지 않고, 빈 공간(위아래, 왼쪽 오른쪽)이 남아 있습니다.
class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
var collectionView: UICollectionView?
var screenSize: CGRect!
var screenWidth: CGFloat!
var screenHeight: CGFloat!
override func viewDidLoad() {
super.viewDidLoad()
screenSize = UIScreen.mainScreen().bounds
screenWidth = screenSize.width
screenHeight = screenSize.height
// Do any additional setup after loading the view, typically from a nib
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
layout.itemSize = CGSize(width: screenWidth / 3, height: screenWidth / 3)
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView!.dataSource = self
collectionView!.delegate = self
collectionView!.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
collectionView!.backgroundColor = UIColor.greenColor()
self.view.addSubview(collectionView!)
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as CollectionViewCell
cell.backgroundColor = UIColor.whiteColor()
cell.layer.borderColor = UIColor.blackColor().CGColor
cell.layer.borderWidth = 0.5
cell.frame.size.width = screenWidth / 3
cell.frame.size.height = screenWidth / 3
cell.textLabel?.text = "\(indexPath.section):\(indexPath.row)"
return cell
}
}
이 두 줄을 추가합니다.
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
다음과 같은 것이 있습니다.
// Do any additional setup after loading the view, typically from a nib.
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
layout.itemSize = CGSize(width: screenWidth/3, height: screenWidth/3)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView!.collectionViewLayout = layout
그러면 모든 공간이 제거되고 그리드 레이아웃이 제공됩니다.
첫 번째 열의 너비를 화면 너비와 같게 하려면 다음 기능을 추가합니다.
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
if indexPath.row == 0
{
return CGSize(width: screenWidth, height: screenWidth/3)
}
return CGSize(width: screenWidth/3, height: screenWidth/3);
}
그리드 레이아웃은 다음과 같이 표시됩니다(첫 번째 셀에 파란색 배경도 추가했습니다).
Swift 3 및 XCode 8에서는 이것이 유효했습니다.이것을 실현하려면 , 다음의 순서에 따라 주세요.
{
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
let width = UIScreen.main.bounds.width
layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
layout.itemSize = CGSize(width: width / 2, height: width / 2)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView!.collectionViewLayout = layout
}
이 코드를 viewDidLoad() 함수에 배치합니다.
특정 상황에서 의 설정UICollectionViewFlowLayout
에viewDidLoad
또는ViewWillAppear
collectionView에는 영향을 주지 않을 수 있습니다.
의 설정UICollectionViewFlowLayout
에viewDidAppear
는 실행 시 셀크기의 변경을 확인할 수 있습니다.
Swift 3의 또 다른 솔루션:
extension YourViewController : UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let collectionViewWidth = collectionView.bounds.width
return CGSize(width: collectionViewWidth/3, height: collectionViewWidth/3)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 20
}
}
Swift 3을 찾으시는 경우 다음 절차를 따르십시오.
func viewDidLoad() {
//Define Layout here
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
//Get device width
let width = UIScreen.main.bounds.width
//set section inset as per your requirement.
layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
//set cell item size here
layout.itemSize = CGSize(width: width / 2, height: width / 2)
//set Minimum spacing between 2 items
layout.minimumInteritemSpacing = 0
//set minimum vertical line spacing here between two lines in collectionview
layout.minimumLineSpacing = 0
//apply defined layout to collectionview
collectionView!.collectionViewLayout = layout
}
이는 Xcode 8.0과 Swift 3에서 확인됩니다.
let layout = myCollectionView.collectionViewLayout as? UICollectionViewFlowLayout
layout?.minimumLineSpacing = 8
스위프트 4, 스위프트 5, 가장 쉬운 방법!
작성 불필요UICollectionViewFlowLayout()
인스턴스, 구현만UICollectionViewDelegateFlowLayout
를 참조해 주세요.
extension MyCollectionView: UICollectionViewDelegateFlowLayout {
// Distance Between Item Cells
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 20
}
// Cell Margin
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
}
}
스위프트 4
let collectionViewLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout
collectionViewLayout?.sectionInset = UIEdgeInsetsMake(0, 20, 0, 40)
collectionViewLayout?.invalidateLayout()
Swift 5 : 동적 셀 폭을 가진 셀 간에 균등하게 분산된 공간을 최대한 활용하기 위해 최소 CellWidth 값을 제공하여 다음 코드 스니펫을 사용할 수 있습니다.
private func collectionViewLayout() -> UICollectionViewLayout {
let layout = UICollectionViewFlowLayout()
layout.sectionHeadersPinToVisibleBounds = true
// Important: if direction is horizontal use minimumItemSpacing instead.
layout.scrollDirection = .vertical
let itemHeight: CGFloat = 240
let minCellWidth :CGFloat = 130.0
let minItemSpacing: CGFloat = 10
let containerWidth: CGFloat = self.view.bounds.width
let maxCellCountPerRow: CGFloat = floor((containerWidth - minItemSpacing) / (minCellWidth+minItemSpacing ))
let itemWidth: CGFloat = floor( ((containerWidth - (2 * minItemSpacing) - (maxCellCountPerRow-1) * minItemSpacing) / maxCellCountPerRow ) )
// Calculate the remaining space after substracting calculating cellWidth (Divide by 2 because of left and right insets)
let inset = max(minItemSpacing, floor( (containerWidth - (maxCellCountPerRow*itemWidth) - (maxCellCountPerRow-1)*minItemSpacing) / 2 ) )
layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
layout.minimumInteritemSpacing = min(minItemSpacing,inset)
layout.minimumLineSpacing = minItemSpacing
layout.sectionInset = UIEdgeInsets(top: minItemSpacing, left: inset, bottom: minItemSpacing, right: inset)
return layout
}
Swift 3+ 및 Xcode 9+의 경우 다음을 사용해 보십시오.
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let collectionWidth = collectionView.bounds.width
return CGSize(width: collectionWidth/3, height: collectionWidth/3)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
코드 한 줄을 쓰는 대신 XCode 옵션이 있습니다. Collection View를 선택하고 탐색기로 이동하여 "최소 간격"을 변경합니다.
Swift 3 및 XCode 8에서는 이것이 유효했습니다.이것을 실현하려면 , 다음의 순서에 따라 주세요.
viewDidLoad()
{
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
var width = UIScreen.main.bounds.width
layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
width = width - 10
layout.itemSize = CGSize(width: width / 2, height: width / 2)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView!.collectionViewLayout = layout
}
언급URL : https://stackoverflow.com/questions/28325277/how-to-set-cell-spacing-and-uicollectionview-uicollectionviewflowlayout-size-r
'programing' 카테고리의 다른 글
SQL Server 2000 데이터베이스에 열려 있는 트랜잭션을 나열하는 방법이 있습니까? (0) | 2023.04.10 |
---|---|
Git - '가정 변경 없음'과 '스킵 워크트리'의 차이점 (0) | 2023.04.10 |
Protocol Buffer vs Json - 하나를 선택하는 경우 (0) | 2023.04.05 |
스프링 부트 비활성화/오류 매핑 (0) | 2023.04.05 |
같은 도메인에 다른 /서버를 배치하는 방법 (0) | 2023.04.05 |