프로그래밍 방식으로 UICollectionViewCell 너비 및 높이를 설정하는 방법
나는 CollectionView
. 자동 레이아웃을 사용할 때 셀의 크기가 변경되지 않고 변경됩니다.
이제는 크기를 예를 들어 변경하고 싶습니다.
//var size = CGSize(width: self.view.frame.width/10, height: self.view.frame.width/10)
내 설정을 시도 CellForItemAtIndexPath
collectionCell.size = size
그래도 작동하지 않습니다.
달성하는 방법이 있습니까?
편집 :
대답은 CollectionView 너비와 높이 자체 만 변경하는 것입니다. 제약 조건에 충돌이있을 수 있습니까? 어떤 아이디어?
이 방법을 사용하여 사용자 지정 셀 높이 너비를 설정합니다.
이 프로토콜을 추가해야합니다.
UICollectionViewDelegate
UICollectionViewDataSource
UICollectionViewDelegateFlowLayout
목표 -C
@interface YourViewController : UIViewController<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(CGRectGetWidth(collectionView.frame), (CGRectGetHeight(collectionView.frame)));
}
Swift 4 이상
extension YourViewController: UICollectionViewDelegate {
//Write Delegate Code Here
}
extension YourViewController: UICollectionViewDataSource {
//Write DataSource Code Here
}
extension YourViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: screenWidth, height: screenWidth)
}
}
선언에 프로토콜을 추가해야합니다 UICollectionViewDelegateFlowLayout
.class
class MyCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout
{
//MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
return CGSize(width: 100.0, height: 100.0)
}
}
마침내 답을 얻었습니다. 확장 UICollectionViewDelegateFlowLayout
해야합니다. 위의 답변으로 작동해야합니다.
신속한 4.1
CollectionView의 크기를 변경하는 방법에는 두 가지가 있습니다.
첫 번째 방법 ->이 프로토콜 추가 UICollectionViewDelegateFlowLayout
for 제 경우에는 셀을 한 줄에 세 부분으로 나누고 싶습니다. 아래 코드를 작성했습니다.
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource ,UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
// In this function is the code you must implement to your code project if you want to change size of Collection view
let width = (view.frame.width-20)/3
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collectionData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
if let label = cell.viewWithTag(100) as? UILabel {
label.text = collectionData[indexPath.row]
}
return cell
}
}
두 번째 방법은 ->은 당신 하지 않습니다 추가해야 우리 UICollectionViewDelegateFlowLayout을 하지만 당신은 몇 가지 코드를 작성할 필요가 있는있는 viewDidLoad를 함수 아래 코드로 대신
class ViewController: UIViewController {
@IBOutlet weak var collectionView1: UICollectionView!
var collectionData = ["1.", "2.", "3.", "4.", "5.", "6.", "7.", "8.", "9.", "10.", "11.", "12."]
override func viewDidLoad() {
super.viewDidLoad()
let width = (view.frame.width-20)/3
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: width, height: width)
}
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collectionData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
if let label = cell.viewWithTag(100) as? UILabel {
label.text = collectionData[indexPath.row]
}
return cell
}
}
첫 번째 방법 또는 두 번째 방법으로 코드를 작성하면 위와 동일한 결과를 얻을 수 있습니다. 내가 썼어. 그것은 나를 위해 일했습니다
iPhone 크기에 따른 크기 비율 :
iPhone 크기와 관련하여 셀의 너비와 높이를 다르게하기 위해 수행 할 수있는 작업은 다음과 수행 할 수 있습니다.
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let width = (self.view.frame.size.width - 12 * 3) / 3 //some width
let height = width * 1.5 //ratio
return CGSize(width: width, height: height)
}
이 대답이 작동 선택 셀에서 AutoLayout 제한 조건을 선택해야합니다.
컬렉션보기에는 레이아웃 개체가 있습니다. 귀하의 경우에는 아마도 흐름 레이아웃 ( UICollectionViewFlowLayout ) 일 것입니다. 흐름 레이아웃의 itemSize
속성을 설정합니다 .
Swift3 및 Swift4 에서는 UICollectionViewDelegateFlowLayout 을 추가하고 다음 과 같이 구현 하여 셀 크기를 설명 수 있습니다 .
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 100)
}
또는 프로그래밍 방식으로 UICollectionView를 생성하는 경우 다음과 같이 할 수 있습니다.
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal //this is for direction
layout.minimumInteritemSpacing = 0 // this is for spacing between cells
layout.itemSize = CGSize(width: view.frame.width, height: view.frame.height) //this is for cell size
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
swift4 swift 4 ios collection view collectionview example xcode 최신 코드 작업 샘플
상단의 델리게이트 섹션에 추가
UICollectionViewDelegateFlowLayout
이 기능을 사용하십시오
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (self.view.frame.size.width - 20) / 3 //some width
let height = width * 1.5 //ratio
return CGSize(width: width, height: height)
}
///// 샘플 전체 코드
@IBOutlet weak var cvContent : UICollectionView 로 컬렉션에 대한 참조를 제공합니다 .
뷰 컨트롤러에 올리기
import UIKit
class ViewController : UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var arrVeg = [String]()
var arrFruits = [String]()
var arrCurrent = [String]()
@IBOutlet weak var cvContent: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
arrVeg = ["Carrot","Potato", "Tomato","Carrot","Potato", "Tomato","Carrot","Potato", "Tomato","Carrot","Potato", "Tomato"]
arrVeg = ["Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange"]
arrCurrent = arrVeg
}
//MARK: - CollectionView
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (self.view.frame.size.width - 20) / 3 //some width
let height = width * 1.5 //ratio
return CGSize(width: width, height: height)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrCurrent.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ContentCollectionViewCell
cell.backgroundColor = UIColor.green
return cell
}
}
아래 방법을 시도하십시오
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: 100.0, height: 100.0)
}
프로그래밍 방식으로 Swift 5
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
//Provide Width and Height According to your need
let cellWidth = UIScreen.main.bounds.width / 10
let cellHeight = UIScreen.main.bounds.height / 10
layout.itemSize = CGSize(width: cellWidth, height: cellHeight)
//You can also provide estimated Height and Width
layout.estimatedItemSize = CGSize(width: cellWidth, height: cellHeight)
//For Setting the Spacing between cells
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
return UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
}()
다른 방법은 흐름 레이아웃에서 직접 값을 설정하는 것입니다.
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: size, height: size)
이것은 내 버전이며 귀하의 요구 사항에 따라 셀 크기를 제공합니다.
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(CGRectGetWidth(collectionView.frame)/4, CGRectGetHeight(collectionView.frame)/4);
}
'ProgramingTip' 카테고리의 다른 글
Linux에서 사용중인 메모리 프로세스의 양을 확인하는 방법은 무엇입니까? (0) | 2020.12.02 |
---|---|
Windows 8/10에서 NetBeans IDE 확장 (0) | 2020.12.02 |
android : actionBarStyle에는 API 레벨 11이 필요합니다. (0) | 2020.12.02 |
16 진수를 RGBA로 변환 (0) | 2020.12.02 |
OS X의 디렉토리에있는 모든 파일의 파일 변경 (0) | 2020.12.02 |