ios - Resizing UICollectionViewCells on rotation changes currently visible cells -
this question has answer here:
i have paginated, horizontally scrolling uicollectionview
each cell takes size of view/device screen, , 1 cell appears @ time. i'm experiencing issue on device rotation, cells transition correct new size, position of cells off.
before rotation:
after rotation:
on rotation, how can not resize collection view cells ensure current cell stays visible?
i've boiled problem down simple example without custom flow layout.
setting size of cells collectionview
frame's size (the collection view size of view controller holding it):
func collectionview(collectionview: uicollectionview, layout collectionviewlayout: uicollectionviewlayout, sizeforitematindexpath indexpath: nsindexpath) -> cgsize { return collectionview.frame.size }
attempting handle rotation in viewwilllayoutsubviews
:
override func viewwilllayoutsubviews() { super.viewwilllayoutsubviews() guard let flowlayout = collectionview.collectionviewlayout as? uicollectionviewflowlayout else { return } flowlayout.itemsize = collectionview.frame.size flowlayout.invalidatelayout() }
actually, if call invalidatelayout()
in viewwilllayoutsubviews
, setting itemsize
here shouldn't necessary, sizeforitematindexpath
called when layout recreated.
i've tried manually scrolling first visible cell during rotation after setting new itemsize, shows no improvement:
if let item = collectionview.indexpathsforvisibleitems().first { collectionview.scrolltoitematindexpath(item, atscrollposition: .centeredhorizontally, animated: true) }
you should handle content offset of uicollectionview
, in view controller try override viewwilltransitiontosize
function uicontentcontainer
protocol, this:
override func viewwilltransitiontosize(size: cgsize, withtransitioncoordinator coordinator: uiviewcontrollertransitioncoordinator) { super.viewwilltransitiontosize(size, withtransitioncoordinator: coordinator) let offset = yourcollectionview?.contentoffset; let width = yourcollectionview?.bounds.size.width; let index = round(offset!.x / width!); let newoffset = cgpointmake(index * size.width, offset!.y); yourcollectionview?.setcontentoffset(newoffset, animated: false) coordinator.animatealongsidetransition({ (context) in yourcollectionview?.reloaddata() yourcollectionview?.setcontentoffset(newoffset, animated: false) }, completion: nil) }
Comments
Post a Comment