Estoy trabajando con UICollectionView
. Estoy intentando cargar unas imágenes (Ya lo he logrado), y cuando cargo la vista por primera vez todo va perfecto, pero cuando regreso a la vista anterior y vuelvo a entrar al CollectionView
las imágenes se han reajustado.
Primera carga:
Segunda Carga:
Este es el código de mi CollectionViewCell
:
class PhotoCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var photo: UIImageView!{
didSet {
photo.contentMode = UIViewContentMode.ScaleAspectFill//ScaleToFill//ScaleAspectFit//ScaleToFill
photo.clipsToBounds = true
}
}
}
Y la parte donde cargo mis imágenes:
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PhotoCollectionViewCell
let seccion = items[indexPath.row]
// Configure the cell
cell.backgroundColor = UIColor.redColor()
cell.label.text = String(indexPath.row)
let imageURL = NSURL( string: seccion.value! as! String)
cell.photo.sd_setImageWithURL(imageURL)
return cell}
Y la ubicación del UIImageview
:
Agrego lo siguiente por si estoy haciendo algo mal en la definición del tamaño de las celdas:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let width = (collectionView.frame.size.width / 3)-10
let heigth = width
return CGSizeMake(width, heigth)
}
// En viewDidLoad.
collectionView!.contentInset = UIEdgeInsets(top: 5, left: 0, bottom: 10, right: 0)
Editado 16-sept-2016
Después de agregar algunas otras imágenes he visto que el cambio de tamaño del UIImageView
es "temporal", se reajusta después de dar scroll.
EDITADO 17-Septiembre-2016
Bien, después de buscar por aquí y por allá he logrado que funcione, pero sigo sin comprender.
He añadido a mi CollectionViewCell
:
override func layoutIfNeeded() {
super.layoutIfNeeded()
}
Y en mi clase CollectionView
dentro del collectionView(...cellForItemAtIndexPath) -> UICollectionViewCell
Despues de let cell = collectionView.dequeueReusa....
he añadido:
cell.setNeedsLayout()
Esta línea es indiferente, funciona igual esté o no esté. ¿Por qué?.
cell.layoutIfNeeded()
y la cosa funciona, ahora mis imágenes se cargan correctamente, sin embargo olvidemos que he hecho lo anterior y pasemos a la parte donde descargo mis datos y agreguemos:
self.collectionView?.layoutIfNeeded()
Después de:
self.collectionView?.reloadData()
Y también funciona. ¿Por qué funciona? y ¿cuál de ambas soluciones es la mejor?