Comment configurer UICollectionViewCell Width and Height de manière programmatique
je suis en train de mettre en œuvre un CollectionView.
Quand J'utilise Autolayout, mes cellules ne changeront pas la taille, mais leur alignement.
maintenant je préférerais changer leurs tailles En par exemple
//var size = CGSize(width: self.view.frame.width/10, height: self.view.frame.width/10)
j'ai essayé de réglage dans mon CellForItemAtIndexPath
collectionCell.size = size
il ne fonctionne pas bien.
Est-il un moyen pour y parvenir?
modifier:
il semble que les réponses ne changeront que la largeur et la hauteur de mon champ de vision m'. Y a-t-il conflit possible dans les contraintes? Toutes les idées sur qui ?
11 réponses
utilisez cette méthode pour définir la largeur de la hauteur des cellules.
assurez-vous d'ajouter ce protocoles
UICollectionViewDelegate
UICollectionViewDataSource
UICollectionViewDelegateFlowLayout
objectif-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,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
         return CGSize(width: screenWidth, height: screenWidth)
    }
}
assurez-vous d'ajouter le protocole UICollectionViewDelegateFlowLayout dans votre class déclaration
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)
    }
}
Enfin eu la réponse.
Vous devez étendre UICollectionViewDelegateFlowLayout
Cela devrait fonctionner avec les réponses ci-dessus. 
voici ce que vous pouvez faire pour avoir une largeur et une hauteur différentes pour les cellules en ce qui concerne la taille de l'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)
}
et peut-être vous devriez également désactiver vos contraintes D'AutoLayout sur la cellule pour que cette réponse fonctionne.
 la vue collection a un mise en page objet. Dans votre cas, c'est probablement une  présentation du flux (Uicollection Viewflowlayout). Réglez la mise en page du flux itemSize propriété. 
swift 4.1
vous avez 2 façons de changer la taille de CollectionView.
Premier -> ajouter ce protocole  Uicollection Viewdelegateflowlayout
pour 
Dans mon cas, je veux diviser la cellule en 3 parties dans une ligne. Je n'ai ce code ci-dessous
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
    }
}
Deuxième ->ne pas ajouter Uicollection Viewdelegateflowlayout mais vous il faut écrire un code dans fonction viewDidload au lieu de cela comme le code ci-dessous
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
    }
}
quoi que vous écriviez un code comme la première ou la seconde façon, vous obtiendrez le même résultat que ci-dessus. Je l'ai écrit. Il a travaillé pour moi
Essayez ci-dessous la méthode
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSize(width: 100.0, height: 100.0)
}
swift4 swift 4 iOS collection view collectionview exemple Xcode dernier exemple de travail de code
ajouter ceci dans la section "délégué" du haut
Uicollection Viewdelegateflowlayout
et utilisez cette fonction
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)
}
///// exemple de code complet
créer la cellule collection view et Collection View dans storyboard donner la référence à la collection comme
  @IBOutlet faible var cvContent: UICollectionView!
coller ceci dans le contrôleur de vue
import UIKit
class ViewController: UIViewController, Uicollection Viewdelegate, Uicollection Viewdatasource, Uicollection Viewdelegateflowlayout {
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
}
}
une autre façon est de définir la valeur directement dans la mise en page
    let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
    layout.itemSize = CGSize(width: size, height: size)
dans Swift3 et Swift4 vous pouvez changer la taille des cellules en ajoutant Uicollection Viewdelegateflowlayout et la mise en œuvre, il est comme ceci :
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 100, height: 100)
    }
ou si créer UICollectionView par programmation, vous pouvez le faire comme ceci :
    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)
C'est ma version, trouvez votre rapport adéquat pour obtenir la taille de la cellule selon votre condition.
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
return CGSizeMake(CGRectGetWidth(collectionView.frame)/4, CGRectGetHeight(collectionView.frame)/4); 
} 
