Populate Collection cell afterwards Swift - swift

I have a mini game in Single-view-app project with item inventory (CollectionView). Its structure in main.Storyboard: CollectionView -> cell -> ContentView -> inventoryImageView. When the game starts items.count of empty cells are generated. Whenever a user taps on imageView of an item he finds, I want this imageView to populate the most left and available cell of the inventory. Something like:
cell.inventoryImageView = itemImageView
How can I access this left unpopulated cell?
The code is:
struct Items {
let imageName: String
var location = (0, 0)
}
var key = Items(imageName: "icons8-key-50")
var chest = Items(imageName: "icons8-closed-treasure-chest-50")
var rock = Items(imageName: "icons8-rock-50")
var bone = Items(imageName: "icons8-human-bone-50")
var mushroom = Items(imageName: "icons8-mushroom-50")
var items = [Items]()
override func viewDidLoad() {
items = [key, chest, rock, bone, mushroom]
}
when user clicks Start button this func gets triggered for every item :
func createItems(imageName: String) {
let imageNamePNG = "\(imageName).png"
let itemImage = UIImage(named: imageNamePNG)
let itemImageView = UIImageView(image: itemImage) itemImageView.frame = CGRect(x: 70, y: 0, width: 63, height: 63)
itemImageView.frame = CGRect(x: Int.random(in: 70...294), y: Int.random(in: 100...543), width: 63, height: 63)
view.addSubview(itemImageView)
createdImages.append(itemImageView)
}
cell creation part:
// MARK: - UICollectionViewDataSource protocol
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! CollectionViewCell
return cell
}

I don't quite understand what you want to do but I hope this code could help you.
CustomCollectionViewCell.swift
import UIKit
class CustomCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var inventoryImageView: UIImageView!
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var collectionView: UICollectionView!
#IBOutlet weak var imageButton: UIButton!
var key = Items(imageName: "img-1")
var chest = Items(imageName: "img-2")
var rock = Items(imageName: "img-3")
var bone = Items(imageName: "img-4")
var mushroom = Items(imageName: "img-5")
var items = [Items]()
var index = 0
var createdImages = [Items]()
override func viewDidLoad() {
super.viewDidLoad()
self.items = [key, chest, rock, bone, mushroom]
self.imageButton.setImage(UIImage(named: self.items[index].imageName), for: .normal)
}
#IBAction func imageButtonAction(_ sender: Any) {
index += 1
if index >= items.count{
index = 0
}
self.imageButton.setImage(UIImage(named: self.items[index].imageName), for: .normal)
self.createdImages.append(self.items[index])
self.collectionView.reloadData()
}
}
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.createdImages.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell
cell.inventoryImageView.image = UIImage(named: self.createdImages[indexPath.item].imageName)
return cell
}
}
Items.swift
struct Items {
let imageName: String
var location = (0, 0)
}

Related

Update Segmented Progress Bar When CollectionView Index is Changed Swift

Working Example Video
I am trying to create an onboarding view such as Instagram stories with a progress bar on top of the view.
So far I was able to animate to the second or third index in the given time. This animation also changes stack view progress bar. But when I try to scroll to the next or previous collection view index I can not show this action inside the progress bar.
I can read the current page index with page control but can not reflect this reading to progress bar.
class OnboardingViewController: UIViewController, SegmentedProgressBarDelegate {
#IBOutlet weak var collectionView: UICollectionView!
#IBOutlet weak var stackView: UIStackView!
private var spb: SegmentedProgressBar!
var currentPage = 0
lazy var pageControl: UIPageControl = {
let pageControl = UIPageControl()
pageControl.numberOfPages = slides.count
return pageControl
}()
//Burası Presenter'dan gelecek.
var slides: [OnboardingSlide] = [
OnboardingSlide(title: "Delicious Dishes", image: #imageLiteral(resourceName: "1")),
OnboardingSlide(title: "World-Class Chefs", image: #imageLiteral(resourceName: "2")),
OnboardingSlide(title: "Instant World-Wide Delivery", image: #imageLiteral(resourceName: "3"))
]
override func viewDidLoad() {
super.viewDidLoad()
spb = SegmentedProgressBar(numberOfSegments: slides.count, duration: 3)
spb.frame = CGRect(x: 15, y: 56, width: collectionView.frame.width - 30, height: 4)
spb.delegate = self
spb.topColor = UIColor.white
spb.bottomColor = UIColor.white.withAlphaComponent(0.25)
spb.padding = 2
collectionView.delegate = self
collectionView.dataSource = self
stackView.addArrangedSubview(spb)
spb.startAnimation()
collectionView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tappedView)))
}
func segmentedProgressBarChangedIndex(index: Int) {
updateView(index: index)
}
override var prefersStatusBarHidden: Bool {
return true
}
func segmentedProgressBarFinished() {
print("Finished!")
}
#objc private func tappedView() {
spb.isPaused = !spb.isPaused
}
private func updateView(index: Int) {
print("index: \(index)")
let indexPath = IndexPath(row: index, section: 0)
collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}
#IBAction func loginButtonTapped(_ sender: UIButton) {
}
#IBAction func signupButtonTapped(_ sender: UIButton) {
}
}
extension OnboardingViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return slides.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: OnboardingCollectionViewCell.identifier, for: indexPath) as! OnboardingCollectionViewCell
cell.setup(slides[indexPath.row])
return cell
}
}
extension OnboardingViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let width = scrollView.frame.width
currentPage = Int(scrollView.contentOffset.x / width)
pageControl.currentPage = currentPage
updateView(index: currentPage)
print("current page: \(currentPage)")
}
}
I have used
https://github.com/D-32/SegmentedProgressBar
as the segmentedProgressBar
class OnboardingCollectionViewCell: UICollectionViewCell {
static let identifier = String(describing: OnboardingCollectionViewCell.self)
#IBOutlet weak var slideImageView: UIImageView!
#IBOutlet weak var slideTitleLabel: UILabel!
func setup(_ slide: OnboardingSlide) {
slideImageView.image = slide.image
slideTitleLabel.text = slide.title
}
}
struct OnboardingSlide {
let title: String
let image: UIImage
}
extension OnboardingViewController: UICollectionViewDelegateFlowLayout {
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
if scrollView.panGestureRecognizer .translation(in: view).x > 0 {
spb.rewind()
} else {
spb.skip()
}
}
}
with this, I was able to understand if collection view was scrolled left or right. Thus calling related functions inside the spb does the trick.

How can I update a UICollectionView from another class?

I am trying this for a couple of days now and haven't achieved anything yet. What I am trying to do is when a user picks a User item form the ViewController class, I want to save it in Realm and show it in the CollectionView of the SavedInterestsViewController class. I use a delegate pattern as suggested in this post How to access and refresh a UITableView from another class in Swift, but unfortunately I still receive nil, I guess because the GC removed the collectionView outlet already right? (please correct me if I misunderstood it). However, how can I get this to work by using a delegate pattern? Here is my code, this is the class where the user Picks a new User-item:
protocol ViewControllerDelegate {
func didUpdate(sender: ViewController)
}
class ViewController: UIViewController {
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var collectionView: UICollectionView!
var delegate: ViewControllerDelegate?
let numberOfTweets = 5
let realm = try! Realm()
var image = UIImage()
var imageArray: [String] = []
var userArray: [User] = []
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionCell")
searchBar.delegate = self
}
}
extension ViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
print("One second...")
let functionClass = NetworkingFunctions()
var loopCount = 0
functionClass.getWikipediaAssumptions(for: searchBar.text!) { [self] (articleArray) in
self.userArray.removeAll()
for x in articleArray {
functionClass.performWikipediaSearch(with: x, language: WikipediaLanguage("en")) { (user) in
self.userArray.append(user)
collectionView.reloadData()
loopCount += 1
}
}
}
}
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return userArray.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionViewCell
let image = UIImage.init(data: userArray[indexPath.item].image as Data)
cell.userImage.image = image
cell.nameLabel.text = userArray[indexPath.item].name
cell.userImage.layer.borderColor = image?.averageColor?.cgColor
if userArray[indexPath.item].checked == false {
cell.checkmark.isHidden = true
} else {
cell.checkmark.isHidden = false
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if userArray[indexPath.item].checked == false {
userArray[indexPath.item].checked = true
collectionView.reloadData()
let newUser = User()
newUser.image = userArray[indexPath.item].image
newUser.name = userArray[indexPath.item].name
newUser.checked = true
try! realm.write {
realm.add(newUser)
}
self.delegate = SavedInterestsViewController()
self.delegate?.didUpdate(sender: self)
}
else {
userArray[indexPath.item].checked = false
collectionView.reloadData()
}
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = UIScreen.main.bounds.width/3 - 10
let height = width
return CGSize(width: width, height: height)
}
}
class User: Object {
#objc dynamic var image: NSData = NSData()
#objc dynamic var name: String = ""
#objc dynamic var checked: Bool = false
}
... and this is the class where I want to show the selected item, after the User clicked on the 'Back' Button of the navigation controller of the ViewController class:
class SavedInterestsViewController: UIViewController, ViewControllerDelegate {
func didUpdate(sender: ViewController) {
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
#IBOutlet weak var addButton: UIBarButtonItem!
#IBOutlet weak var collectionView: UICollectionView!
let realm = try! Realm()
var userArray: [User] = []
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionCell")
fetchDataFromRealm()
}
#IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "SavedToNew", sender: self)
}
func fetchDataFromRealm() {
userArray.append(contentsOf: realm.objects(User.self))
collectionView.reloadData()
}
}
extension SavedInterestsViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return userArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionViewCell
let image = UIImage.init(data: userArray[indexPath.item].image as Data)
cell.userImage.image = image
cell.nameLabel.text = userArray[indexPath.item].name
cell.userImage.layer.borderColor = image?.averageColor?.cgColor
if userArray[indexPath.item].checked == false {
cell.checkmark.isHidden = true
} else {
cell.checkmark.isHidden = false
}
return cell
}
}
extension SavedInterestsViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = UIScreen.main.bounds.width/3 - 10
let height = width
return CGSize(width: width, height: height)
}
}
in your code you have lines
self.delegate = SavedInterestsViewController()
self.delegate?.didUpdate(sender: self)
but it do mostly nothing - you set the delegate to newly created class, didUpdate it - but I don't see any use of it - you don't present it in any way.
If I understand you right - you have SavedInterestsViewController, from it - you open ViewController, do something and when back to SavedInterestsViewController. (I can be wrong with your flow - correct me if so)
In this flow - you have delegate property in ViewController, but it must be of type SavedInterestsViewController. And you have to set it to SavedInterestsViewController when you open ViewController from it. And later in ViewController you have to call didUpdate method of delegate.

How to expand an xib collectionviewcell height dynamically?

I am looking to make my xib custom collection view cell height dynamic when clicked upon rather than using a fixed variable height.
I have tried using constraints on the heights of the cell in the storyboard.
This is the MotCollectionViewCell.swift code:
import UIKit
protocol ExpandedCellDelegate:NSObjectProtocol{
func topButtonTouched(indexPath:IndexPath)
}
class MotCollectionViewCell: UICollectionViewCell {
#IBOutlet var heightConstraint: NSLayoutConstraint!
#IBOutlet var topButton: UIButton!
weak var delegate:ExpandedCellDelegate?
public var indexPath:IndexPath!
#IBAction func topButtonTouched(_ sender: UIButton) {
if let delegate = self.delegate{
delegate.topButtonTouched(indexPath: indexPath)
}
}
#IBOutlet var testLbl: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
This is the BarChartViewControllerCell.Swift code :
import UIKit
import Charts
class BarChartViewController: UIViewController, ChartViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, ExpandedCellDelegate {
// Bar Chart Properties
#IBOutlet var barChartView: BarChartView!
var dataEntry: [BarChartDataEntry] = []
// Chart Data
var result = [String]()
var mileage = [String]()
var colours = [UIColor]()
var list = [Tester]()
// Collection View properties
#IBOutlet var collectionView: UICollectionView!
var expandedCellIdentifier = "MotCollectionViewCell"
var cellWidth:CGFloat{
return collectionView.frame.size.width
}
var expandedHeight : CGFloat = 258
var notExpandedHeight : CGFloat = 75
var dataSource = ["data0","data1","data2","data3","data4"]
var isExpanded = [Bool]()
override func viewDidLoad() {
super.viewDidLoad()
isExpanded = Array(repeating: false, count: dataSource.count)
//Register nib cell
let nibCell = UINib(nibName: expandedCellIdentifier, bundle: nil)
collectionView.register(nibCell, forCellWithReuseIdentifier: expandedCellIdentifier)
}
// Collection View functions
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: expandedCellIdentifier, for: indexPath) as! MotCollectionViewCell
cell.indexPath = indexPath
cell.delegate = self
//configure Cell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if isExpanded[indexPath.row] == true{
return CGSize(width: cellWidth, height: expandedHeight)
}else{
return CGSize(width: cellWidth, height: notExpandedHeight)
}
}
func topButtonTouched(indexPath: IndexPath) {
isExpanded[indexPath.row] = !isExpanded[indexPath.row]
UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.9, options: UIView.AnimationOptions.curveEaseInOut, animations: {
self.collectionView.reloadItems(at: [indexPath])
}, completion: { success in
print("success")
})
}
}
When the cell is clicked, the cell expands to the height which I declared as a constant, what I am trying to achieve is have the cell expand according to the data within it.

Load specific items in second UI Collection View after tap a cell?

I have a collection view with different category cell. When tap one of this I'd like to load all recipes with that category.
I have two class:
a. CategoryModel - to manage the category
class CategoryModel: NSObject, NSCoding
{
var nameCategory: String
var iconCategory: UIImage
var recipes = [RecipeModel]()
b. RecipeModel
class RecipeModel: NSObject, NSCoding
{
var nameRecipe: String
var quantityRecipe: String
var recipeTime: String
var preparationTime: String
var cookingTime: String
var bakingTempRecipe: String
var difficultyLevelRecipe: String
var imageRecipe: UIImage
var ingredients: [IngredientModel]
var directions: [DirectionModel]
var categoryRecipe: String
I suppose to insert someone in the CategoryCollViewController when I selected the one of all categories... but I don't know to do it!
Someone help me, please!
RecipeCollViewcontroller
class RecipeCollViewController: UICollectionViewController, UITextFieldDelegate
{
var category: CategoryModel!
var recipesList = [RecipeModel]()
struct Storyboard
{
static let leftAndRightPaddings: CGFloat = 2.0
static let numberOfItemsPerRow: CGFloat = 2.0
}
override func viewDidLoad()
{
super.viewDidLoad()
longPressGesture()
RecipeDataManager.shared.recipeController = self
title = category.nameCategory
navigationController?.navigationBar.prefersLargeTitles = true
let collectionViewWidth = collectionView?.frame.width
let itemWidth = (collectionViewWidth! - Storyboard.leftAndRightPaddings) / Storyboard.numberOfItemsPerRow
let layout = collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: itemWidth, height: 250)
}
override func numberOfSections(in collectionView: UICollectionView) -> Int
{
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return category.recipesList.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RecipeCell", for: indexPath) as! RecipeViewCell
let recipe = category.recipesList[indexPath.item]
cell.labelNameRecipe.text = recipe.nameRecipe
cell.imageViewRecipe.image = recipe.imageRecipe
cell.labelPrepareTime.text = String(recipe.recipeTimeInt)
cell.labelQuantityFor.text = recipe.quantityRecipe
return cell
}
override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
RecipeDataManager.shared.recipes.remove(at: indexPath.row)
collectionView.deleteItems(at: [indexPath])
}
Declare ** recipesList** in the next screen's ViewController.
var recipesList = [RecipeModel]()
Now in your categoryViewController, implement this CollectionViewDelegate method
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let vc=self.storyboard?.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as? YourViewControllerClass
recipesList = self.categoryList[indexPath.row].recipes
self.navigationController?.pushViewController(vc!, animated: true)
}
Access your recipes array from ** var recipesList** from declared earlier

Two CollectionViews in One Viewcontroller

I´m trying to put two CollectionViews in one Viewcontroller. I have tried many solutions, but every time the data only shows in the first CollectionsView. The data I want to put in both CollectionView is the same.
How do I do this
My code
import UIKit
import Firebase
import MobileCoreServices
import AVKit
private let reuseIdentifier = "Cell"
var databaseRefRoom: FIRDatabaseReference {
return FIRDatabase.database().reference()
}
class RoomViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITableViewDelegate {
//ScrollView
#IBOutlet weak var favoritesBtn: UIButton!
#IBOutlet weak var yourChatBtn: UIButton!
#IBOutlet weak var mostPopularBtn: UIButton!
//RoomCollectionView -> RoomViewCollectionViewCell
var rooms = [Room]()
#IBOutlet weak var collectionView: UICollectionView!
//RoomViewController material
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Chuloo"
self.navigationController?.isNavigationBarHidden = false
favoritesBtn.setTitle("Favorites", for:.normal)
favoritesBtn.titleLabel?.textColor = UIColor.white
favoritesBtn.titleLabel?.font = UIFont(name: "AppleSDGothicNeo-Bold", size: 14)
favoritesBtn.backgroundColor = UIColor.orange
yourChatBtn.setTitle("Your Chat", for:.normal)
yourChatBtn.titleLabel?.textColor = UIColor.white
yourChatBtn.titleLabel?.font = UIFont(name: "AppleSDGothicNeo-Bold", size: 14)
yourChatBtn.backgroundColor = UIColor.red
mostPopularBtn.setTitle("Most Popular", for:.normal)
mostPopularBtn.titleLabel?.textColor = UIColor.white
mostPopularBtn.titleLabel?.font = UIFont(name: "AppleSDGothicNeo-Bold", size: 14)
mostPopularBtn.backgroundColor = UIColor.blue
//RoomCollectionView -> Display CollectionView i ScrollView -> Extension
collectionView.dataSource = self
collectionView.delegate = self
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "dd.MMMM.yyyy - hh:mm:ss a"
formatter.amSymbol = "AM"
formatter.pmSymbol = "PM"
let result = formatter.string(from: date)
//Hide backButton
self.navigationItem.setHidesBackButton(true, animated: false)
//RoomCollectionView -> DataService fetch from Server
DataService.dataService.fetchDataFromServer { (room) in
self.rooms.append(room)
let indexPath = IndexPath(item: self.rooms.count - 1, section: 0)
self.collectionView?.insertItems(at: [indexPath])
}
//Online User Status
let usersRef = databaseRefRoom.child("online")
let currentUserRef = usersRef.child((FIRAuth.auth()?.currentUser?.displayName)!)
currentUserRef.setValue("online")
currentUserRef.onDisconnectRemoveValue()
//Database User child Online Status
let usersRefUser = databaseRefRoom.child("users").child((FIRAuth.auth()?.currentUser?.displayName)!).child("Online Status").child("online")
usersRefUser.setValue(result)
let usersRefOffline = databaseRefRoom.child("users").child((FIRAuth.auth()?.currentUser?.displayName)!).child("Online Status")
usersRefOffline.onDisconnectUpdateChildValues(["offline": result])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
//RoomCollectionView -> Display
extension RoomViewController {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return rooms.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "roomCell", for: indexPath) as! RoomViewCollectionViewCell
let room = rooms[indexPath.row]
cell.layer.cornerRadius = 4
cell.layer.borderColor = UIColor(red: 248.0/255.0, green: 248.0/255.0, blue: 248.0/255.0, alpha: 1.0).cgColor
cell.layer.borderWidth = 1
cell.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25).cgColor
cell.layer.shadowOffset = CGSize(width: 0, height: 2)
cell.layer.shadowOpacity = 0.5
cell.layer.shadowRadius = 1.0
cell.layer.masksToBounds = false
// Configure the cell
cell.configureCell(room: room)
return cell
}
func collectionView(collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath) -> CGSize {
return CGSize(width: view.frame.width / 2 - 5, height: view.frame.width / 2 - 5)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
}
Let's walk through what is the problem of your code and how you could solve it.
First:
You mentioned that:
I´m trying to put two CollectionViews in one Viewcontroller.
but your code doesn't seems to be containing two collection views. So what you should do is:
class ViewController: UIViewController {
.
.
.
#IBOutlet weak var collectionView1: UICollectionView!
#IBOutlet weak var collectionView2: UICollectionView!
.
.
.
}
Make sure that you are connecting both of collection views to the view controller.
Second:
I have tried many solutions, but every time the data only shows in the
first CollectionsView. The data I want to put in both CollectionView
is the same.
Make sure -after implementing the first step- is to conform to both collection views dataSource and delegate:
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
.
.
.
#IBOutlet weak var collectionView1: UICollectionView!
#IBOutlet weak var collectionView2: UICollectionView!
override func viewDidLoad() {
.
.
.
collectionView1.dataSource = self
collectionView1.delegate = self
collectionView2.dataSource = self
collectionView2.delegate = self
.
.
.
}
.
.
.
}
That's should leads to achieve requirement of "I want to put in both CollectionView is the same".
Also
What if you need to let each of the collection view to read from a different data source? you could let the dateSource/delegate method to recognize the collection view by setting a tag it, as follows:
In viewDidLoad() method:
// setting tags:
collectionView1.tag = 101
collectionView2.tag = 102
Thus:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collectionView === collectionView1 ? dataSource1.count : dataSource2.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellID", for: indexPath)
let currentObject = collectionView === collectionView1 ? dataSource1[indexPath.row] : dataSource2[indexPath.row]
.
.
.
return cell
}
And so on...
Hope this helped.