프로그래밍 방식으로 UICollectionView셀 너비 및 높이를 설정하는 방법
다음을 구현하려고 합니다.CollectionView자동 레이아웃을 사용하면 셀 크기가 변경되지 않고 셀 정렬이 변경됩니다.
이제는 차라리 사이즈를 예를 들어 변경하고 싶습니다.
var size = CGSize(width: self.view.frame.width/10, height: self.view.frame.width/10)
설정을 시도했습니다.CellForItemAtIndexPath
collectionCell.size = size
하지만 효과가 없었습니다.
이것을 달성할 수 있는 방법이 있습니까?
편집:
답변은 내 컬렉션 보기 너비와 높이만 변경하는 것 같습니다.제약 조건에 충돌이 있을 수 있습니까?그것에 대한 아이디어가 있습니까?
이 방법을 사용하여 사용자 지정 셀 높이 너비를 설정합니다.
이 프로토콜을 추가해야 합니다.
UICollectionViewDelegate
UICollectionViewDataSource
UICollectionViewDelegateFlowLayout
swift 5 또는 xcode 11 이상을 사용하는 경우 설정해야 합니다.Estimate Size로.none제대로 작동하기 위해 스토리보드를 사용합니다.이 값을 아래보다 낮게 설정하지 않으면 코드가 예상대로 작동하지 않습니다.
스위프트 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)
}
}
목표-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)));
}
스토리보드를 사용하고 UICollectionViewDelegateFlowLayout을 재정의하는 경우 swift 5 및 Xcode 11에서도 추정 크기를 없음으로 설정합니다.
프로토콜을 추가해야 합니다.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
CollectionView의 크기를 변경하려면 두 가지 방법이 있습니다.
첫 번째 방법 -> 이 프로토콜 UICollectionViewDelegateFlowLayout 추가
저의 경우 셀을 한 줄에 3개로 나누고 싶습니다.아래 코드를 수행했습니다.
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 크기와 관련하여 셀의 너비와 높이를 다르게 설정할 수 있는 방법은 다음과 같습니다.
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)
}
또한 이 답변이 작동하려면 셀에서 자동 레이아웃 제약 조건을 비활성화해야 합니다.
Swift3 및 Swift4에서는 UICollectViewDelegateFlowLayout을 추가하고 다음과 같이 구현하여 셀 크기를 변경할 수 있습니다.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 100)
}
또는 프로그래밍 방식으로 UICollectView를 생성하는 경우 다음과 같이 수행할 수 있습니다.
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)
집합 뷰에 레이아웃 개체가 있습니다.이 경우 흐름 레이아웃(UICollectionViewFlowLayout)일 수 있습니다.흐름 레이아웃의 설정itemSize소유물.
swift4 swift4 ios 컬렉션 뷰 컬렉션 보기 예제 xcode 최신 코드 작업 샘플
상단의 위임 섹션에 이 항목 추가
UICollectionView위임자 흐름 레이아웃
그리고 이 기능을 사용합니다.
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)
}
샘플 전체 코드
and in 을 렉션뷰컬작및성뷰셀로 참조합니다.
@IButlet 한약 varcvContent : UICollectionView!
View 컨트롤러에 붙여넣기
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
}
}
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)
}()
스위프트 5
완전한 프로그래밍 방식 솔루션
// In viewDidLoad
if let cvLayout = horizontalCV.collectionViewLayout as? UICollectionViewFlowLayout{
cvLayout.estimatedItemSize = .zero
}
extension TUIViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: (collectionView.frame.size.width)/7, height:50)
}
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
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets.zero
}
}
보너스 : 장치가 회전할 때 핸들 ::
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
// Have the collection view re-layout its cells.
coordinator.animate(
alongsideTransition: { _ in self.horizontalCV.collectionViewLayout.invalidateLayout() },
completion: { _ in }
)
}
아래 방법을 사용해 보십시오.
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: 100.0, height: 100.0)
}
스위프트 5
다음 프로토콜 추가
- `UICollectionViewDelegate`
- `UICollectionViewDataSource`
- `UICollectionViewDelegateFlowLayout`
그러면 코드가 다음과 같이 표시됩니다.
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)
}
}
이제 이 기능을 적용하기 위한 마지막이자 중요한 단계는 View 컨트롤러 내의 videDidLoad 기능으로 이동하는 것입니다.
override func viewDidLoad() {
super.viewDidLoad()
collection.dataSource = self // Add this
collection.delegate = self // Add this
// Do any additional setup after loading the view.
}
딜러가 어떤 클래스인지 알려주지 않으면 작동하지 않습니다.
다른 방법은 흐름 레이아웃에서 직접 값을 설정하는 것입니다.
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: size, height: size)
셀, 하기 위해 했습니다. 즉, 따서라셀 션섹에서에으섹션을로성서의에속정설해야하며다필니합서요방는이대법위이리법을기한하현방구board으▁view▁so에▁delegate▁method▁method▁:▁forcontro에ller▁your▁need▁this▁implementing▁you,따▁cell▁story▁estimate▁had▁for▁from▁size▁cell▁view▁in▁andcontro며▁collect▁section라boardion▁needview다▁attribute니하▁in필▁cell▁story합요▁for▁to서,이ller▁none▁settingoptional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
UICollectionViewDelegateFlowLayout 메서드를 사용해 보십시오.Xcode 11 이상에서는 스토리보드에서 견적 크기를 없음으로 설정해야 합니다.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout:
UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let padding: CGFloat = 170
let collectionViewSize = advertCollectionView.frame.size.width - padding
return CGSize(width: collectionViewSize/2, height: collectionViewSize/2)
}
간단한 방법:
간단한 고정 사이즈만 필요한 경우:
class SizedCollectionView: UIICollectionView {
override func common() {
super.common()
let l = UICollectionViewFlowLayout()
l.itemSize = CGSize(width: 42, height: 42)
collectionViewLayout = l
}
}
그게 다야.
스토리보드에서 클래스를 UICollectionView에서 SizeCollectionView로 변경하면 됩니다.
하지만!!!
기본 클래스는 Initializer의 "UI 'I' CollectionView"이며, "I"입니다.
컬렉션 보기에 이니셜라이저를 추가하는 것은 쉽지 않습니다.일반적인 접근 방식은 다음과 같습니다.
이니셜라이저가 있는 집합 뷰...
import UIKit
class UIICollectionView: UICollectionView {
private var commoned: Bool = false
override func didMoveToWindow() {
super.didMoveToWindow()
if window != nil && !commoned {
commoned = true
common()
}
}
internal func common() {
}
}
대부분의 프로젝트에서는 "이니셜라이저가 있는 컬렉션 뷰"가 필요합니다.그래서 당신은 아마 어쨌든 가지고 있을 것입니다.UIICollectionView(Initializer에 대한 추가 I에 유의하십시오!).
Swift 5, Programmatic UICollection View 설정 셀 너비 및 높이
// MARK: MyViewController
final class MyViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
private lazy var collectionViewLayout: UICollectionViewFlowLayout = {
let layout = UICollectionViewFlowLayout()
let spacing: CGFloat = 1
let numOfColumns: CGFloat = 3
let itemSize: CGFloat = (UIScreen.main.bounds.width - (numOfColumns - spacing) - 2) / 3
layout.itemSize = CGSize(width: itemSize, height: itemSize)
layout.minimumInteritemSpacing = spacing
layout.minimumLineSpacing = spacing
layout.sectionInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing)
return layout
}()
private lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: collectionViewLayout)
collectionView.backgroundColor = .white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.translatesAutoresizingMaskIntoConstraints = false
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
configureCollectionView()
}
private func configureCollectionView() {
view.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
collectionView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
])
collectionView.register(PhotoCell.self, forCellWithReuseIdentifier: "PhotoCell")
}
// MARK: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
cell.backgroundColor = .red
return cell
}
}
// MARK: PhotoCell
final class PhotoCell: UICollectionViewCell {
lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.layer.masksToBounds = true
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init?(coder:) not implemented")
}
func setupViews() {
addSubview(imageView)
NSLayoutConstraint.activate([
topAnchor.constraint(equalTo: topAnchor),
bottomAnchor.constraint(equalTo: bottomAnchor),
leadingAnchor.constraint(equalTo: leadingAnchor),
trailingAnchor.constraint(equalTo: trailingAnchor)
])
}
}
사용자 경우itemSize뷰의, 은 당신의 컬렉션 뷰의 너비를 .UICollectionViewFlowLayout의prepare()방법.여기 이 기술을 보여주는 WWDC 비디오가 있습니다.
class MyLayout: UICollectionViewFlowLayout {
override func prepare() {
super.prepare()
guard let collectionView = collectionView else { return }
itemSize = CGSize(width: ..., height: ...)
}
}
UICollectionViewController를 사용하지 않는 경우에는 UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout을 설정하여 적합성을 추가해야 합니다.
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
그런 다음 ViewController에 추가되는 컬렉션 보기에 대리자를 설정해야 합니다.
collectionView.delegate = self
collectionView.dataSource = self
마지막으로 레이아웃을 컬렉션 보기에 추가해야 합니다.
let collectionLayout = UICollectionViewFlowLayout()
collectionView.collectionViewLayout = collectionLayout
다음 단계 후에 func에서 크기를 변경할 수 있습니다.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
아주 간단한 방법:
class YourCollection: UIViewController,
UICollectionViewDelegate,
UICollectionViewDataSource {
"UICollectionViewDelegateFlowLayout"을 추가해야 합니다. 그렇지 않으면 자동 완성이 없습니다.
class YourCollection: UIViewController,
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout {
"sizeForItemAt..."를 입력합니다.끝났습니다!
class YourCollection: UIViewController,
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 37, height: 63)
}
바로 그겁니다.
예를 들어, "각 셀이 전체 집합 보기를 채웁니다"는 경우:
guard let b = view.superview?.bounds else { .. }
return CGSize(width: b.width, height: b.height)
storyBoard 사용자에 대한 대답은 "in size inspector(검사자 크기에서 수집 셀 크기를 사용자 정의에서 자동으로 변경)"입니다.
이것은 제 버전입니다, 당신의 요구에 맞는 셀 크기를 얻기 위해 당신의 적절한 비율을 찾아보세요.
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(CGRectGetWidth(collectionView.frame)/4, CGRectGetHeight(collectionView.frame)/4);
}
언급URL : https://stackoverflow.com/questions/38028013/how-to-set-uicollectionviewcell-width-and-height-programmatically
'programing' 카테고리의 다른 글
| 최상위 수준 요청에 대해 대기(거짓) 구성 (0) | 2023.05.03 |
|---|---|
| Jupyter Python 노트북의 모든 데이터 프레임 열 표시 (0) | 2023.05.03 |
| Mobile Safari에서 뷰포트 확대/축소를 비활성화하려면 어떻게 해야 합니까? (0) | 2023.05.03 |
| Bash에서 백 틱에 해당하는 cmd/PowerShell은 얼마입니까? (0) | 2023.05.03 |
| 열 이름별 판다 데이터 프레임 가입 (0) | 2023.05.03 |


