I would like to set the numberOfItemsInSection of my collectionView at runtime. I will be changing the value programmatically at runtime quite often and would like to know how.
I have an array of images to display in my UICollectionView (1 image per UICollectionViewCell), and the user can change the category of the images to display, which will also change the number of images to display. When the view loads, the numberOfItemsInSection is set to the count of the allClothingStickers array. But number this is too high. The array that does get displayed is the clothingStickersToDisplay array which is a subset of the allClothingStickers array.
There is this error after some scrolling:
fatal error: Array index out of range
This is because the number of items has become smaller, but the UICollectionView numberOfItemsInSectionproperty has not changed to be a smaller number.
I have this function that sets the number of cells in the UICollectionView before runtime.
func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return self.numberOfItems
}
This function to set the stickersToDisplay array (and I want to update the numberOfItemsInSection property here):
func setStickersToDisplay(category: String) {
clothingStickersToDisplay.removeAll()
for item in self.allClothingStickers {
let itemCategory = item.object["category"] as! String
if itemCategory == category {
clothingStickersToDisplay.append(item)
}
}
self.numberOfItems = clothingStickersToDisplay.count
}
This is the function that returns the cell to display:
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath)
-> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(
identifier,forIndexPath:indexPath) as! CustomCell
let sticker = clothingStickersToDisplay[indexPath.row]
let name = sticker.object["category"] as! String
var imageView: MMImageView =
createIconImageView(sticker.image, name: name)
cell.setImageV(imageView)
return cell
}
EDIT: Oh yeah, and I need to reload the UICollectionView with the new clothingStickersToDisplay at the same place that I update it's numberOfItemsInSection
I think what you should do is to clothingStickersToDisplay a global array declaration.
Instead of using that self.numberOfItems = clothingStickersToDisplay.count
Change this function to
func setStickersToDisplay(category: String) {
clothingStickersToDisplay.removeAll()
for item in self.allClothingStickers {
let itemCategory = item.object["category"] as! String
if itemCategory == category {
clothingStickersToDisplay.append(item) //<---- this is good you have the data into the data Structure
// ----> just reload the collectionView
}
}
}
In the numberOfItemsInSection()
return self.clothingStickersToDisplay.count
Related
I have a collectionview nested inside a collectionview cell and I need the number of cells in that collectionview to be equal to a dictionary value that the super cell carries.
So to reiterate, each cell is a room object and contains a title, a description and an array of members. I want the members.count to equal the number of cells inside the interior collection view for that specified index.
It originally thought that it would be best to set this in the the super cells cellForItemAtIndexPath function as seen below,
if section == 0 {
cell = liveCell
// these work fine
let room = rooms[indexPath.row]
liveCell.liveStreamNameLabel.text = room.groupChatName
liveCell.descriptionLabel.text = room.groupChatDescription
// this does not
liveCell.profileCV.numberOfItems(inSection: 0) = room.members?.count
return cell
}
but it appears that numberOfItems(inSection: ) is a get method.
I tried accessing the array count at the actual interior collectionviews numberOfItemsInSection function however it returns zero each time.
lazy var homeController: HomeController = {
let hc = HomeController()
hc.liveCell = self
return hc
}()
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// does not work
// let room = homeController.rooms[indexPath.row]
// return homeController.room.count
// doesn't crash but returns zero everytime
return homeController.rooms.count
}
Any suggestions?
I learned the UICollectionView inside UITableViewCell from this tutorial.
It works perfectly only when all of the collection views have the same numberOfItemsInSection, so it can scroll and won't cause Index out of range error, but if the collection view cells numberOfItemsInSection are different, when I scroll the collection view it crashes due to Index out of range.
I found the reason that when I scroll the tableview, the collection view cell index path updated according to the bottom one, but the collection view I scrolled is top one so it does't remember the numberOfItemsInSection, so it will crash due to Index out of range.
ps: it is scrollable, but only when that table cell at the bottom, because its numberOfItemsInSection is correspond to that cell and won't cause Index out of range.
This is the numberOfItemsInSection of My CollectionView, i actually have two collection view but i think this is not the problem
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
var numberOfItemsInSection: Int = 0
if collectionView == self.collectionview_categorymenu {
let categories = self.json_menucategory["menu_categories"].arrayValue
numberOfItemsInSection = categories.count
} else {
let menuitems = self.json_menucategory["menu_items"].arrayValue
let item_data = menuitems[self.itemimages_index].dictionaryValue
let menu_item_images = item_data["menu_item_images"]?.arrayValue
numberOfItemsInSection = (menu_item_images?.count)!
print(numberOfItemsInSection)
}
return numberOfItemsInSection
}
This is the cellForItemAt indexPath of my CollectionView:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.collectionview_categorymenu {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CategoryMenuCell", for: indexPath) as! CategoryMenuCell
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemImagesCell", for: indexPath) as! ItemImagesCell
let menuitems = self.json_menucategory["menu_items"].arrayValue
let item_data = menuitems[self.itemimages_index].dictionaryValue
let menu_item_images = item_data["menu_item_images"]?.arrayValue
print(menu_item_images!)
let itemimage_data = menu_item_images?[indexPath.item].dictionaryValue
print("===\(indexPath.item)===")
let itemimage_path = itemimage_data?["image"]?.stringValue
let itemimage_detail = itemimage_data?["detail"]?.stringValue
if let itemimage = cell.imageview_itemimage {
let image_url = itemimage_path?.decodeUrl()
URLSession.shared.dataTask(with: NSURL(string: image_url!) as! URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print("error")
return
}
DispatchQueue.main.async(execute: { () -> Void
in
itemimage.image = UIImage(data: data!)!
})
}).resume()
}
if let description = cell.textview_description {
description.text = itemimage_detail
}
if let view = cell.view_description {
view.isHidden = true
}
return cell
}
}
The problem is probaby that you are returning the same number every time for numberOfItemsInSection what you want to do is return the number of items in each array. From the link you sent they do this:
func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return model[collectionView.tag].count
}
The other possibility is that you are returning the wrong array when cellForItemAtIndexPath please check that you are using the tag attribute correctly
So they get the count of each array within the model. Without seeing any of your code its very difficult to actually see where your error is coming from.
I have a collection view that scrolls horizontally and each cell pushes to a detail view upon a tap. When I load the app, I have it print the object at index. At first it will load the one cell it is supposed to. But when I scroll over one space it prints off two new ids, and then begins to associate the data of the last loaded cell with the one currently on the screen, which is off by one spot now. I have no clue how to resolve this, my best guess is there is some way to better keep up with the current index or there is something in the viewDidAppear maybe I am missing. Here is some code:
open var currentIndex: Int {
guard (self.collectionView) != nil else { return 0 }
return Int()
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ExpandCell", for: indexPath) as! ExpandingCollectionViewCell
let object = self.imageFilesArray[(indexPath).row] as! PFObject
cell.nameLabel.text = object["Name"] as! String
whatObject = String(describing: object.objectId)
print(whatObject)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let object = self.imageFilesArray[(indexPath as NSIndexPath).row]
guard let cell = collectionView.cellForItem(at: indexPath) as? ExpandingCollectionViewCell else { return }
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "EventDetailViewController") as! EventDetailViewController
nextViewController.lblName = nameData
nextViewController.whatObj = self.whatObject
self.present(nextViewController, animated:false, completion:nil)
}
Does anyone know a better way to set the current index so I am always pushing the correct data to the next page?
The data source that is setting the elements of the cell can keep count of index that can also be set as a property and can be used to retrieve back from the cell to get correct current index.
EventDetailViewController is your UICollectionViewController subclass I assume.
If this is correct then you need to implement on it:
A method that tells the collection how many items there are in the datasource.
//1
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1 // you only have 1 section
}
//2
override func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return array.count// this is the number of models you have to display... they will all live in one section
}
A method that tells the collection which cellView subclass to use for that given row.
-A method that populates the cell with it's datasource.
Follow this tutorial from which I extracted part of the code, they convey this core concepts pretty clearly.
Reusing, as per Apple's docs happens for a number of cells decided by UIKit, when you scroll up a little bit 2 or N cells can be dequed for reusing.
In summary, with this three methods you can offset your collection into skipping the one record that you want to avoid.
Happy coding!
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.
Let's say you set up a bunch of image views inside a UICollectionView's cells (from an array of image names) and make their alpha 0.5 by default when you set up the items.
Then you make the image view's alpha to 1.0 in the didSelectItemAtIndexPath func, so it becomes alpha 1 when the user taps.
This works when the user taps a cell, but it does not persist if the user scrolls, because the cell is being re-used by the UI on some other level.
The result is another cell farther down the way (when scrolling) becomes alpha 1.0 and the original cell you selected reverts back to its previous alpha 0.5 appearance.
I understand that this is all done to make things more efficient on the device, but I still have not figured out how to make it work properly where the selected item persists.
ANSWER
Apple does provide a selectedBackgroundView for cells that you can use to change the background color, shadow effect, or outline etc. They also allow you to use an image inside the cell with a "default" and "highlighted" state.
Both of those methods will persist with the selection properly.
However, if you wish to use attributes or different elements than one of those provided for indicating your selected state, then you must use a separate data model element that includes a reference to the currently selected item. Then you must reload the viewcontroller data when the user selects an item, resulting in the cells all being redrawn with your selected state applied to one of the cells.
Below is the jist of the code I used to solve my problem, with thanks to Matt for his patience and help.
All of this can be located inside your main UICollectionView Controller class file, or the data array and struct can be located inside their own swift file if you need to use it elsewhere in the project.
Data and data model:
let imagesArray=["image1", "image2", "image3", ...]
struct Model {
var imageName : String
var selectedState : Bool
init(imageName : String, selectedState : Bool = false){
self.imageName = imageName
self.selectedState = selectedState
}
}
Code for the UICollectionView Controller
// create an instance of the data model for images and their status
var model = [Model]()
#IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// build out a data model instance based on the images array
for i in 0..<imagesArray.count {
model.append(Model(imageName: imagesArray[i]))
// the initial selectedState for all items is false unless otherwise set
}
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imagesArray.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// when the collectionview is loaded or reloaded...
let cell:myCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! myCollectionViewCell
// populate cells inside the collectionview with images
cell.imageView.image = UIImage(named: model[indexPath.item].imageName)
// set the currently selected cell (if one exists) to show its indicator styling
if(model[indexPath.item].selectedState == true){
cell.imageView.alpha = 1.0
} else {
cell.imageView.alpha = 0.5
}
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// when a cell is tapped...
// reset all the selectedStates to false in the data model
for i in 0..<imagesArray.count {
model[i].selectedState = false
}
// set the selectedState for the tapped item to true in the data model
model[indexPath.item].selectedState = true
// refresh the collectionView (triggering cellForItemAtIndexPath above)
self.collectionView.reloadData()
}
but it does not persist if the user scrolls, because the cell is being re-used by the UI on some other level
Because you're doing it wrong. In didSelect, make no change to any cells. Instead, make a change to the underlying data model, and reload the collection view. It's all about your data model and your implementation of cellForItemAtIndexPath:; that is where cells and slots (item and section) meet.
Here's a simple example. We have just one section, so our model can be an array of model objects. I will assume 100 rows. Our model object consists of just an image name to go into this item, along with the knowledge of whether to fade this image view or not:
struct Model {
var imageName : String
var fade : Bool
}
var model = [Model]()
override func viewDidLoad() {
super.viewDidLoad()
for i in 0..<100 {
// ... configure a Model object and append it to the array
}
}
override func collectionView(
collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return 100
}
Now, what should happen when an item is selected? I will assume single selection. So that item and no others should be marked for fading in our model. Then we reload the data:
override func collectionView(cv: UICollectionView,
didSelectItemAtIndexPath indexPath: NSIndexPath) {
for i in 0..<100 {model[i].fade = false}
model[indexPath.item].fade = true
cv.reloadData()
}
All the actual work is done in cellForItemAtIndexPath:. And that work is based on the model:
override func collectionView(cv: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let c = self.collectionView!.dequeueReusableCellWithReuseIdentifier(
"Cell", forIndexPath: indexPath) as! MyCell
let model = self.model[indexPath.item]
c.iv.image = UIImage(named:model.imageName)
c.iv.alpha = model.fade ? 0.5 : 1.0
return c
}
You logic is incorrect. didSelectItemAtIndexPath is used to trigger something when a cell is selected. All this function should contain is this:
let cell:stkCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! stkCollectionViewCell
cell.imageView.alpha = 1.0
selectedIndex = indexPath.item
Then in your cellForItemAtIndexPath function you should have the logic to set the cell because this is where the cells are reused. So this logic should be in there:
if (indexPath.item == selectedIndex){
print(selectedIndex)
cell.imageView.alpha = 1.0
}
else {
cell.imageView.alpha = 0.5
}