tutorial how example custom collection ios swift uicollectionview uicollectionviewlayout

ios - how - UICollectionView Custom Cell para completar el ancho en Swift



uicollectionview swift 4 (8)

He estado tratando de averiguar cómo puedo hacer que la celda ocupe todo el ancho, como se puede ver en la imagen, el ancho entre las celdas es demasiado grande. Estoy usando una celda personalizada con solo una imageView.

Traté de personalizarlo desde el guión gráfico, pero supongo que no hay opción para eso o debería hacerse programáticamente.

mi UICollectionViewController:

@IBOutlet var collectionView2: UICollectionView! let recipeImages = ["angry_birds_cake", "creme_brelee", "egg_benedict", "full_breakfast", "green_tea", "ham_and_cheese_panini", "ham_and_egg_sandwich", "hamburger", "instant_noodle_with_egg.jpg", "japanese_noodle_with_pork", "mushroom_risotto", "noodle_with_bbq_pork", "starbucks_coffee", "thai_shrimp_cake", "vegetable_curry", "white_chocolate_donut"] override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { //#warning Incomplete method implementation -- Return the number of sections return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //#warning Incomplete method implementation -- Return the number of items in the section return recipeImages.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! RecipeCollectionViewCell // Configure the cell cell.recipeImageView.image = UIImage(named: recipeImages[indexPath.row]) return cell }


Necesitas hacer esto programáticamente.

Implemente UICollectionViewDelegateFlowLayout en su controlador de vista y proporcione el tamaño en collectionView:layout:sizeForItemAtIndexPath:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let kWhateverHeightYouWant = 100 return CGSizeMake(collectionView.bounds.size.width, CGFloat(kWhateverHeightYouWant)) }

También querrá llamar a collectionView.collectionViewLayout.invalidateLayout() dentro de viewWillLayoutSubviews() su controlador de viewWillLayoutSubviews() para que cuando las dimensiones de la vista principal cambien (en rotación, por ejemplo), la vista de colección se vuelva a diseñar.


Dentro de su controlador de vista, anule el método viewDidLayoutSubviews

@IBOutlet weak var collectionView: UICollectionView! override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { let itemWidth = view.bounds.width / 3.0 let itemHeight = layout.itemSize.height layout.itemSize = CGSize(width: itemWidth, height: itemHeight) layout.invalidateLayout() } }

( collectionView propiedad collectionView es su collectionView)


Establece itemSize en [UIScreen mainScreen].bounds.size.width/3


En mi caso, suponiendo que cada celda tiene un ancho de 155 y una altura de 220. Si quiero mostrar 2 celdas por fila en un modo vertical y 3 en horizontal.

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { var itemsCount : CGFloat = 2.0 if UIApplication.sharedApplication().statusBarOrientation != UIInterfaceOrientation.Portrait { itemsCount = 3.0 } return CGSize(width: self.view.frame.width/itemsCount - 20, height: 220/155 * (self.view.frame.width/itemsCount - 20)); }


La mejor solución es cambiar el itemSize de su UICollectionViewFlowLayout en viewDidLayoutSubviews . Ahí es donde puede obtener el tamaño más preciso de UICollectionView . No es necesario que invoque la invalidación en su diseño, eso ya se hará por usted.


Swift 3

Si está utilizando swift 3, use este método:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { }

Observe los cambios:

  1. agregar _ antes de collectionView en el nombre del método
  2. NSIndexPath cambia a IndexPath

Utilice el siguiente código para establecer el ancho de UICollectionViewCell .

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: screenWidth/3, height: screenWidth/3); }


También en Swift 3,

Asegúrese de que su controlador de vista cumpla con lo siguiente:

UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout