Cells overlapping in UICollectionView - ios

I am displaying the results of a web request to a custom API in an UICollectionView with dynamically sized cells. However, when I call reloadSections after having fetched the data, many of the cells display overlapping.
As the view is scrolled, the cells display in their proper place.
I have tracked down the error to calling reloadSections in the completion block for my web request. Using hardcoded text, the collection view displays properly with the initial layout. If reloadSections is called in the completion block, the error occurs. Below is the relevant code:
override func viewDidLoad() {
super.viewDidLoad()
collectionView.register(UINib.init(nibName: "ExhibitionsCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "ExhibitionsCollectionViewCell")
layout.estimatedItemSize = CGSize(width: 1, height: 1)
collectionView.dataSource = exhibitionsDataSource
collectionView.delegate = self
store.fetchExhibitions {
(exhibitionsResult) -> Void in
switch exhibitionsResult {
case let .success(exhibitions):
print("Successfully found \(exhibitions.count) exhibitions.")
if exhibitions.first != nil {
self.exhibitionsDataSource.exhibitions = exhibitions
}
case let .failure(error):
print("Error fetching exhibitions: \(error)")
self.exhibitionsDataSource.exhibitions.removeAll()
}
// this is the line that produces the erroneous layout
self.collectionView.reloadSections(IndexSet(integer: 0))
}
}
Code making the web request:
func fetchExhibitions(completion: #escaping (ExhibitionsResult) -> Void) {
let url = WebAPI.exhibitionsURL
let request = URLRequest(url: url)
let task = session.dataTask(with: request) {
(data, response, error) -> Void in
let result = self.processExhibitionsRequest(data: data, error: error)
OperationQueue.main.addOperation {
completion(result)
}
}
task.resume()
}
If there is any other code that would be helpful in answering this question, let me know.
Update: I fixed the issue by implementing the following delegate method of UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cell = collectionView.cellForItem(at: indexPath)
let height = cell?.contentView.bounds.height ?? 1
let width = cell?.contentView.bounds.width ?? 1
return CGSize(width: width, height: height)
}
Update2: Upon switching out my fake Lorem Ipsum data for the data actually retrieved from the server the problem resurfaced. However, I was able to finally solve the issue simply by switching the line
self.collectionView.reloadSections(IndexSet(integer: 0))
to
self.reloadData()
I would think that reloadSection(_:) simply performs the same action as reloadData() but for the selected sections and the documentation doesn't seem to indicate otherwise...but either way it works now!

From that code I'm not sure of the reason, but maybe try to implement some of the functions provided by the delegate UICollectionViewDelegateFlowLayout.
Focus on the function
sizeForItemAtIndexPath
Example:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(320, 500);
}

Related

Image on CollectionView cell changes when scrolling

I have a collectionView that has custom cells. Each custom cell has an image in it and other components. The problem I'm having is that when I scroll, the images changes to another images from other cells on the collectionView. I'm gonna put the code that I'm using so it's more clear to see how I'm implementing the collectionView and it's cell.
func registerCell() {
collectionView.register(PageCell.self, forCellWithReuseIdentifier: cellId)
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let pageNumber = Int(targetContentOffset.pointee.x / view.frame.width)
pageControl.currentPage = pageNumber
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return feedTitles.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! PageCell
cell.titleLabel.text = self.feedTitles[indexPath.item].uppercased()
cell.textView.text = self.feedDescription[indexPath.item]
guard let imageURL = URL(string: self.feedImages[indexPath.item]) else {return cell}
cell.imageView.load(url: imageURL)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
This is the code for getting the images from a server:
var feeds: [Feed]?
func getFeed(){
feedService.getFeed() { [weak self](feedRes) in
switch feedRes {
case .success(let successResponse):
print("Success Feed")
if successResponse.data.count < 1 {
} else{
self?.feeds = successResponse.data
self?.feedTitles = self?.feeds?.compactMap({ $0.title
}) ?? ["Titulo Noticia"]
self?.feedImages = self?.feeds?.compactMap({ $0.image
}) ?? ["Imagen"]
self?.feedDescription = self?.feeds?.compactMap({ $0.content
}) ?? ["Descripcion Imagen"]
self?.collectionView.reloadData()
self?.pageControl.numberOfPages = (self?.feedTitles.count)!
self?.pageControl.isHidden = false
}
case .failure(let feedError):
print("Fail Feed \(feedError)")
print(feedError.localizedDescription)
self?.pageControl.isHidden = true
}
}
}
This is the "load" function:
func load(url: URL) {
DispatchQueue.global().async { [weak self] in
if let data = try? Data(contentsOf: url) {
if let image = UIImage(data: data) {
DispatchQueue.main.async {
self?.image = image
}
}
}
}
}
The issue is inside your cell.imageView.load(url: imageURL) implementation.
Downloading an image is an asynchronous operation. When you create a cell - you start an operation and you don't know when it's going to complete. Whenever it completes, it sets the image on your UIImageView instance.
The cell on the other hand is a reuseable component for collectionView and when you scroll, same cell instance that disappeared by going out of screen from top will also reappear by coming in from bottom of the screen. This means that one cell instance can trigger multiple image download requests and it doesn't cancel it's previous in-flight image download request. It also does not know which image download call completed - the last one (or the one before that etc.)
What you need to do is - add some additional protection in the imageView load method so that when a cell (and hence imageView) instance is reused - it only sets the image for last request (not the ones done prior to the last one).
Copy paste following code into your project.
import UIKit
import ObjectiveC.runtime
private var keyTagIdentifier: String?
public extension UIView {
var tagIdentifier: String? {
get { return objc_getAssociatedObject(self, &keyTagIdentifier) as? String }
set { objc_setAssociatedObject(self, &keyTagIdentifier, newValue, .OBJC_ASSOCIATION_RETAIN) }
}
}
Update your image load extension like this
public extension UIImageView {
func load(url: URL) {
// 1. Assign the current request identifier on this instance
let lastRequestIdentifier = url.absoluteString
self.tagIdentifier = lastRequestIdentifier
// 2. Download the image as you are doing today
// 3. After the image has been downloaded and you set the image
// Please check whether we are still interested in same image or not
// This will be written inside your image download completion block
if self.tagIdentifier == lastRequestIdentifier {
self.image = // the image you downloaded
}
}
}
I believe the issue is due to UICollectionView reusing cells. Meaning the cell that disappears from the top, is rendered at the bottom, usually with the same state as the cell that disappeared from the top and vice-versa for the cells at the bottom. You can avoid this behaviour by adding the following to you code to your PageCell,
override func prepareForReuse() {
super.prepareForReuse()
imageView?.image = nil
}

UICollectionViewCell created from XIB will cause flickering during drag and drop

I implement a simple drag and drop sample.
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
private var collectionView: UICollectionView?
var colors: [UIColor] = [
.link,
.systemGreen,
.systemBlue,
.red,
.systemOrange,
.black,
.systemPurple,
.systemYellow,
.systemPink,
.link,
.systemGreen,
.systemBlue,
.red,
.systemOrange,
.black,
.systemPurple,
.systemYellow,
.systemPink
]
override func viewDidLoad() {
super.viewDidLoad()
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.itemSize = CGSize(width: view.frame.size.width/3.2, height: view.frame.size.width/3.2)
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
//collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
let customCollectionViewCellNib = CustomCollectionViewCell.getUINib()
collectionView?.register(customCollectionViewCellNib, forCellWithReuseIdentifier: "cell")
collectionView?.delegate = self
collectionView?.dataSource = self
collectionView?.backgroundColor = .white
view.addSubview(collectionView!)
let gesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture))
collectionView?.addGestureRecognizer(gesture)
}
#objc func handleLongPressGesture(_ gesture: UILongPressGestureRecognizer) {
guard let collectionView = collectionView else {
return
}
switch gesture.state {
case .began:
guard let targetIndexPath = collectionView.indexPathForItem(at: gesture.location(in: self.collectionView)) else {
return
}
collectionView.beginInteractiveMovementForItem(at: targetIndexPath)
case .changed:
collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: collectionView))
case .ended:
collectionView.endInteractiveMovement()
default:
collectionView.cancelInteractiveMovement()
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView?.frame = view.bounds
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return colors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.backgroundColor = colors[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.size.width/3.2, height: view.frame.size.width/3.2)
}
func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
return true
}
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let item = colors.remove(at: sourceIndexPath.row)
colors.insert(item, at: destinationIndexPath.row)
}
}
However, I notice that, if my UICollectionViewCell is created with XIB, it will randomly exhibit flickering behaviour, during drag and drop.
The CustomCollectionViewCell is a pretty straightforward code.
CustomCollectionViewCell.swift
import UIKit
extension UIView {
static func instanceFromNib() -> Self {
return getUINib().instantiate(withOwner: self, options: nil)[0] as! Self
}
static func getUINib() -> UINib {
return UINib(nibName: String(describing: self), bundle: nil)
}
}
class CustomCollectionViewCell: UICollectionViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
Flickering
By using the following code
let customCollectionViewCellNib = CustomCollectionViewCell.getUINib()
collectionView?.register(customCollectionViewCellNib, forCellWithReuseIdentifier: "cell")
It will have the following random flickering behaviour - https://youtu.be/CbcUAHlRJKI
No flickering
However, if the following code is used instead
collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
Things work fine. There are no flickering behaviour - https://youtu.be/QkV2HlIrXK8
May I know why it is so? How can I avoid the flickering behaviour, when my custom UICollectionView is created from XIB?
Please note that, the flickering behaviour doesn't happen all the time. It happens randomly. It is easier to reproduce the problem using real iPhone device, than simulator.
Here's the complete sample code - https://github.com/yccheok/xib-view-cell-cause-flickering
While we are rearranging cells in UICollectionView (gesture is active), it handles all of the cell movements for us (without having us to worry about changing dataSource while the rearrange is in flight).
At the end of this rearrange gesture, UICollectionView rightfully expects that we will reflect the change in our dataSource as well which you are doing correctly here.
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let item = colors.remove(at: sourceIndexPath.row)
colors.insert(item, at: destinationIndexPath.row)
}
Since UICollectionView expects a dataSource update from our side, it performs following steps -
Call our collectionView(_:, moveItemAt:, to:) implementation to provide us a chance to reflect the changes in dataSource.
Call our collectionView(_:, cellForItemAt:) implementation for the destinationIndexPath value from call #1, to re-create a new cell at that indexPath from scratch.
Okay, but why would it perform step 2 even if this is the correct cell to be at that indexPath?
It's because UICollectionView doesn't know for sure whether you actually made those dataSource changes or not. What happens if you don't make those changes? - now your dataSource & UI are out of sync.
In order to make sure that your dataSource changes are correctly reflected in the UI, it has to do this step.
Now when the cell is being re-created, you sometimes see the flicker. Let the UI reload the first time, put a breakpoint in the cellForItemAt: implementation at the first line and rearrange a cell. Right after rearrange completes, your program will pause at that breakpoint and you can see following on the screen.
Why does it not happen with UICollectionViewCell class (not XIB)?
It does (as noted by others) - it's less frequent. Using the above steps by putting a breakpoint, you can catch it in that state.
How to solve this?
Get a reference to the cell that's currently being dragged.
Return this instance from cellForItemAt: implementation.
var currentlyBeingDraggedCell: UICollectionViewCell?
var willRecreateCellAtDraggedIndexPath: Bool = false
#objc func handleLongPressGesture(_ gesture: UILongPressGestureRecognizer) {
guard let cv = collectionView else { return }
let location = gesture.location(in: cv)
switch gesture.state {
case .began:
guard let targetIndexPath = cv.indexPathForItem(at: location) else { return }
currentlyBeingDraggedCell = cv.cellForItem(at: targetIndexPath)
cv.beginInteractiveMovementForItem(at: targetIndexPath)
case .changed:
cv.updateInteractiveMovementTargetPosition(location)
case .ended:
willRecreateCellAtDraggedIndexPath = true
cv.endInteractiveMovement()
default:
cv.cancelInteractiveMovement()
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if willRecreateCellAtDraggedIndexPath,
let currentlyBeingDraggedCell = currentlyBeingDraggedCell {
self.willRecreateCellAtDraggedIndexPath = false
self.currentlyBeingDraggedCell = nil
return currentlyBeingDraggedCell
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.contentView.backgroundColor = colors[indexPath.item]
return cell
}
Will this solve the problem 100%?
NO. UICollectionView will still remove the cell from it's view hierarchy and ask us for a new cell - we are just providing it with an existing cell instance (that we know is going to be correct according to our own implementation).
You can still catch it in the state where it disappears from UI before appearing again. However this time there's almost no work to be done, so it will be significantly faster and you will see the flickering less often.
BONUS
iOS 15 seems to be working on similar problems via UICollectionView.reconfigureItems APIs. See an explanation in following Twitter thread.
Whether these improvements will land in rearrange or not, we will have to see.
Other Observations
Your UICollectionViewCell subclass' XIB looks like following
However it should look like following (1st one is missing contentView wrapper, you get this by default when you drag a Collection View Cell to the XIB from the View library OR create a UICollectionViewCell subclass with XIB).
And your implementation uses -
cell.backgroundColor = colors[indexPath.row]
You should use contentView to do all the UI customization, also note the indexPath.item(vs row) that better fits with cellForItemAt: terminology (There are no differences in these values though). cellForRowAt: & indexPath.row are more suited for UITableView instances.
cell.contentView.backgroundColor = colors[indexPath.item]
UPDATE
Should I use this workaround for my app in production?
NO.
As noted by OP in the comments below -
The proposed workaround has 2 shortcomings.
(1) Missing cell
(2) Wrong content cell.
This is clearly visible in https://www.youtube.com/watch?v=uDRgo0Jczuw Even if you perform explicit currentlyBeingDraggedCell.backgroundColor = colors[indexPath.item] within if block, wrong content cell issue is still there.
The flickering is caused by the cell being recreated at its new position. You can try holding to the cell.
(only the relevant code is shown)
// keeps a reference to the cell being dragged
private weak var draggedCell: UICollectionViewCell?
// the flag is set when the dragging completes
private var didInteractiveMovementEnd = false
#objc func handleLongPressGesture(_ gesture: UILongPressGestureRecognizer) {
switch gesture.state {
case .began:
// keep cell reference
draggedCell = collectionView.cellForItem(at: targetIndexPath)
collectionView.beginInteractiveMovementForItem(at: targetIndexPath)
case .ended:
// reuse the cell in `cellForItem`
didInteractiveMovementEnd = true
collectionView.performBatchUpdates {
collectionView.endInteractiveMovement()
} completion: { completed in
self.draggedCell = nil
self.didInteractiveMovementEnd = false
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// reuse the dragged cell
if didInteractiveMovementEnd, let draggedCell = draggedCell {
return draggedCell
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
...
}

UICollectionView reload data doesn't update cells

I'd like to preface this by saying I'm used to how UITableViews work and am not super familiar with UICollectionView.
What I'm essentially doing is
Add views (including collection view) on screen
featuredCollectionView = UICollectionView(frame: CGRect(x: 0, y: featuredLabel.frame.origin.y + featuredLabel.frame.size.height, width: view.frame.size.width, height: 216), collectionViewLayout: layout)
featuredCollectionView.delegate = self
featuredCollectionView.dataSource = self
featuredCollectionView.register(ItemCollectionViewCell.self, forCellWithReuseIdentifier:
"cell")
featuredCollectionView.backgroundColor = UIColor.fysGray
featuredCollectionView.showsHorizontalScrollIndicator = false
// add view to screen
Load data from network and add to datasource array
func fetchPosts()
{
// note some libs have been changed for x purposes
NetworkClass.loadPosts()
{ (data, error) in
// parse into valid object
// add to datasource array
self.featuredItems.append(item)
// reload data
DispatchQueue.main.async
{
self.featuredCollectionView.reloadData()
}
}
collectionView.reloadData() on main queue as shown above
After calling reload data nothing appears on screen as if it is blank. I've tried reloading from the main queue and inserting/performing batch updates etc. I'm just really confused on how to get this working. Do I have to know the number of items before I load from the network? How can I get this working?
Here if the code for cellForItemAt
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
var item: Item
if collectionView == featuredCollectionView
{
item = featuredItems[indexPath.row]
}
else
{
item = recentlyViewedItems[indexPath.row]
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ItemCollectionViewCell
cell.item = item
return cell
}
Ended up being a problem with the if condition in the cell method. It didn't like it for some reason, so I used two separate view controllers with a container view and it worked like a charm with reloadData()

Photos not showing in collection view

When I open my application it asks me for permission to access my photos. That is all all right. But after accepting, the screen turns black and shows no photos and in my console it says that it has found no photos. Although I have photos on my device.
import UIKit
import Photos
class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var imageArray = [UIImage]()
override func viewDidLoad() {
grabPhotos()
}
func grabPhotos(){
let imgManager = PHImageManager.defaultManager()
let requestOptions = PHImageRequestOptions()
requestOptions.synchronous = true
requestOptions.deliveryMode = .HighQualityFormat
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key:"CreationDate" , ascending: false)]
if let fetchResult : PHFetchResult = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions){
if fetchResult.count > 0 {
for i in 0..<fetchResult.count{
imgManager.requestImageForAsset(fetchResult.objectAtIndex(i) as! PHAsset, targetSize: CGSize(width: 200, height: 200), contentMode: .AspectFill, options: requestOptions, resultHandler: {
image, error in
self.imageArray.append(image!)
})
}
}
else{
print("You have got not photos!")
self.collectionView?.reloadData()
}
}
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageArray.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
let imageView = cell.viewWithTag(1) as! UIImageView
imageView.image = imageArray[indexPath.row]
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let width = collectionView.frame.width / 3 - 1
return CGSize(width: width, height: width)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 1.0
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 1.0
}
}
Most likely the problem here is that you're asking for assets only once. The first time you ask, you get nothing. When you call PHAsset.fetchAssetsWithMediaType, it does two things at the same time: It asks the user for authorization, and because authorization hasn't been granted yet (the authorization prompt is still on screen), it returns an empty fetch result. (And because the fetch result is empty, you can't
If that's the problem, you should see a non-empty fetch result the second time you run your app (because authorization is a one-time thing and persists across launches).
There are a few ways to deal with this...
One is simply to request authorization directly first using requestAuthorization() and fetch assets only after that call's completion handler fires (with a positive result).
Another is to register() your view controller (or some other controller class of yours) as an observer of the Photos library before performing a fetch. Your first fetch before authorization still returns an empty result, but as soon as the user has authorized your app your observer gets a photoLibraryDidChange() call from which you can access the full, "real" fetch results.
Beyond that, there are some other things you're doing that aren't best practice here...
You're requesting images from the PHImageManager for every asset in the library, regardless of whether the user is going to see them. Consider the case of someone whose iCloud Photo Library contains tens of thousands of assets — only the first 30 or so are going to fit on your collection view at once, and the user may never scroll all the way to the end, but you're still fetching thumbnails for Every Image Ever. (And in the case of iCloud assets not on the local device, trigging network activity for lots of thumbnails the user might never see.)
You're getting thumbnails from PHImageManager synchronously and sequentially. Once you get the authorization issue dealt with, your app will probably crash because your for i in 0..<fetchResult.count { imgManager.requestImageForAsset loop blocks the main thread for too long.
Apple provides canonical example code that demonstrates how to use the Photos app to do things like displaying a collection view full of thumbnails. Take a look at AssetGridViewController.swift in that project to see some of the things they're doing:
use PHCachingImageManager to prefetch batches of thumbnails based on the visible area of a collection view
use PHPhotoLibraryObserver to react to changes in a fetch result, including animated collection view updates
handling the interaction between asynchronous fetches and the collection view data source
inserting new assets in the Photos library
1) Subclass a UICollectionViewCell:
import ...
//put this e.g. to the top of your swift file, right after import statements
class PhotoViewCell: UICollectionViewCell {
#IBOutlet weak var myImageView: UIImageView!
}
2) Create a prototype for you cell:
2.1 design it (you may have done before)
2.2 enter an identifier
2.3 enter a class
2.4 CTRL drag from storyboard: from the cell's imageView to the #IBOutlet line (from the step 1)
3) Update your cellForItem method:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! PhotoViewCell {
cell.myImageView.image = imageArray[indexPath.row]
return cell
}
use a class for cell , put imageview in your cell make it an outlet
now write this
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! 'your class name for cell'
cell.Image.image = imageArray[indexPath.row]
return cell
}

How to do zoom in UICollectionView

I have working uicollectionview codes with CustomCollectionViewLayout , and inside have a lot of small cells but user cannot see them without zoom. Also all cells selectable.
I want to add my collection view inside zoom feature !
My clear codes under below.
class CustomCollectionViewController: UICollectionViewController {
var items = [Item]()
override func viewDidLoad() {
super.viewDidLoad()
customCollectionViewLayout.delegate = self
getDataFromServer()
}
func getDataFromServer() {
HttpManager.getRequest(url, parameter: .None) { [weak self] (responseData, errorMessage) -> () in
guard let strongSelf = self else { return }
guard let responseData = responseData else {
print("Get request error \(errorMessage)")
return
}
guard let customCollectionViewLayout = strongSelf.collectionView?.collectionViewLayout as? CustomCollectionViewLayout else { return }
strongSelf.items = responseData
customCollectionViewLayout.dataSourceDidUpdate = true
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
strongSelf.collectionView!.reloadData()
})
}
}
}
extension CustomCollectionViewController {
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return items.count
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items[section].services.count + 1
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CustomCollectionViewCell
cell.label.text = items[indexPath.section].base
return cell
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath cellForItemAtIndexPath: NSIndexPath) {
print(items[cellForItemAtIndexPath.section].base)
}
}
Also my UICollectionView layout properties under below you can see there i selected maxZoom 4 but doesnt have any action !
Thank you !
You don't zoom a collection like you'd zoom a simple scroll view. Instead you should add a pinch gesture (or some other zoom mechanism) and use it to change the layout so your grid displays a different number of items in the visible part of the collection. This is basically changing the number of columns and thus the item size (cell size). When you update the layout the collection can animate between the different sizes, though it's highly unlikely you want a smooth zoom, you want it to go direct from N columns to N-1 columns in a step.
I think what you're asking for looks like what is done in the WWDC1012 video entitled Advanced Collection Views and Building Custom Layouts (demo starts at 20:20) https://www.youtube.com/watch?v=8vB2TMS2uhE
You basically have to add pinchGesture to you UICollectionView, then pass the pinch properties (scale, center) to the UICollectionViewLayout (which is a subclass of UICollectionViewFlowLayout), your layout will then perform the transformations needed to zoom on the desired cell.

Resources