I am working with collection view, all is going well and I want to add function when text field ,outside of collection view, end editing all labels text to be changed.
Here is my code
I tried my variation of newValue() function but no luck.
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIGestureRecognizerDelegate, UITextFieldDelegate {
var lastSelectedIndexPath:IndexPath?
#IBOutlet weak var txtx: UITextField!
var text2 = ["new text", "text2", "text3"]
override func viewDidLoad() {
let toolBar = UIToolbar()
toolBar.sizeToFit()
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(doneButtonClicked))
toolBar.setItems([flexibleSpace,doneButton], animated: false)
doneButton.style = .done
doneButton.tintColor = UIColor.white // should be white
super.viewDidLoad()
ItemCollection.delegate = self
ItemCollection.dataSource = self
txtx.delegate = self
txtx.inputAccessoryView = toolBar
}
#objc func doneButtonClicked() {
view.endEditing(true)
}
// Store the clicked item location
private var section: Int = 0
private var item0 = 0
func newValue() {
//new func here
}
#IBAction func save() {
}
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var ItemCollection: UICollectionView!
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return text2.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = ItemCollection.dequeueReusableCell(withReuseIdentifier: "check", for: indexPath) as? checkCollectionViewCell
cell?.isSelected = (lastSelectedIndexPath == indexPath)
cell?.layer.backgroundColor = colorLiteral(red: 0.1068892553, green: 0.119746305, blue: 0.1270511448, alpha: 1)
cell?.layer.cornerRadius = 10
cell?.backgroundColor = UIColor(red: 0/256, green: 128/256, blue: 255/256, alpha: 0.66)
cell?.az.text = text2[indexPath.row]
cell?.chechButton.backgroundColor = .clear
return cell!
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// text2[indexPath.row] = "Selected"
// self.ItemCollection.reloadItems(at: [indexPath])
guard lastSelectedIndexPath != indexPath else{
return
}
if lastSelectedIndexPath != nil {
ItemCollection.deselectItem(at: lastSelectedIndexPath!, animated: false)
}
let selectedCell = collectionView.cellForItem(at: indexPath) as! checkCollectionViewCell
selectedCell.isSelected = true
lastSelectedIndexPath = indexPath
}
}
What function should I add to update all text by save button.? Thank you)!
add all changed values in array (text2 in your code)
once you update values call this method
self.collectionview.reloadData()
[edited]
func reload(){
self.text2 = ["new data1", "newd ata2" , "new data3"]
self.collectionView.reloadData()
}
Related
I use a UITabBarController to manage the large middle button on the UITabBar. Here is a part of it.
class TabBarController: UITabBarController, UITabBarControllerDelegate, ContentChangedDelegate {
override func viewDidLoad() {
super.viewDidLoad()
setupMiddleButton()
}
func setupMiddleButton() {
let tabBarHeight = tabBar.frame.size.height
let menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: tabBarHeight*1.5, height: tabBarHeight*1.5))
var menuButtonFrame = menuButton.frame
menuButtonFrame.origin.y = view.bounds.height - menuButtonFrame.height/2 - tabBarHeight - 8
menuButtonFrame.origin.x = view.bounds.width/2 - menuButtonFrame.size.width/2
menuButton.frame = menuButtonFrame
menuButton.backgroundColor = UIColor.red
menuButton.layer.cornerRadius = menuButtonFrame.height/2
view.addSubview(menuButton)
let largeConfiguration = UIImage.SymbolConfiguration(scale: .large)
let addIcon = UIImage(systemName: "plus", withConfiguration: largeConfiguration)
menuButton.setImage((addIcon), for: .normal)
menuButton.addTarget(self, action: #selector(menuButtonAction(sender:)), for: .touchUpInside)
view.layoutIfNeeded()
}
#objc private func menuButtonAction(sender: UIButton) {
AddViewController.delegate = self
performSegue(withIdentifier: "addEventSegue", sender: self)
}
}
and I conform another class LifeViewController(I used the class the specify the collecitonView and searchbar and other items in it) to tabBarController but the lifeCollectionView is always nil when implicitly unwrap, Could any one help me, Thank you so much!
class LifeViewController: TabBarController {
let realm = try! Realm()
var reminders : Results<Memorandum>!
let tabBarView = TabBarController()
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet var lifeCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.fetchData()
lifeCollectionView.delegate = self
lifeCollectionView.dataSource = self
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
self.fetchData()
}
override func reloadCollection() {
if let life = self.lifeCollectionView {
life.reloadData()
} else {
print("life found nil")
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
performSegue(withIdentifier: "editing", sender: self)
}
func fetchData() {
reminders = realm.objects(Memorandum.self)
}
}
//MARK: - CollectionView
extension LifeViewController {
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: lifeCollectionView.frame.width/2.1, height: lifeCollectionView.frame.width/2.1)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return reminders.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let reminder = reminders[indexPath.item]
let lifeCell = lifeCollectionView.dequeueReusableCell(withReuseIdentifier: "lifeCell", for: indexPath) as! ReminderCell
lifeCell.configureCell(date: reminder.dateReminder, importance: UIColor(hex: reminder.color)!, name: reminder.title, depict: reminder.depiction)
lifeCell.layer.cornerRadius = 12
return lifeCell
}
}
But when I change back to conform the LifeViewController to UIViewController, and other collection view protocols the IBOutlet, delegate and dataSource work again? Why is that?
I want to make things like this.
(1). if I press one of that button(A) among 31. that number(A) turn red.
(2). then if I press another button(B) then (A) turn black again and then (B) turn red.
**
class ViewController: UICollectionViewController {
var collectionViewCell = CollectionViewCell()
let data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier : "MyCell")
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! CollectionViewCell
cell.Label.text = String(data[indexPath.row])
return cell
}
}
class CollectionViewCell: UICollectionViewCell {
#IBOutlet weak var Label: UILabel!
#IBOutlet weak var button: UIButton!
#IBAction func buttonPressed(_ sender: UIButton) {
if Label.textColor == .red{
Label.textColor = .black
} else if Label.textColor == .black{
Label.textColor = .red
}
}
public override func awakeFromNib() {
super.awakeFromNib()
}
}
You have to use isSelected and func setSelected(_ selected: Bool, animated: Bool) {
But first you need to know that in Swift we use camelCase styling for variables.
Now we would have to change a little bit your cell implementation:
class CollectionViewCell: UICollectionViewCell {
#IBOutlet weak var label: UILabel!
#IBOutlet weak var button: UIButton!
public override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
label.textColor = .red
} else {
label.textColor = .black
}
}
#IBAction func buttonPressed(_ sender: UIButton) {
self.isSelected = !self.isSelected
}
}
Also don't forget to update cell.Label.text = String(data[indexPath.row]) to cell.label.text = String(data[indexPath.row])
EDIT
As Leo Darbus pointed out it would be better to use isSelected.toggle() than self.isSelected = !self.isSelected, since it's already provided by system
You have to save the row number of the selected cell in the view controller.
Rather than modifying the color in the cell add a callback closure. In cellForRow handle the callback to set the current row to red and the previous row to black by reloading the row.
Something like this
class ViewController: UICollectionViewController {
var selectedRow : Int?
let data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier : "MyCell")
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! CollectionViewCell
cell.Label.textColor = indexPath.item == selectedRow ? .red : .black
cell.callback = { [unowned self] in
if let row = self.selectedRow {
self.selectedRow = indexPath.item
collectionView.reloadItems(at: [IndexPath(item: row, section: 0)])
}
cell.Label.textColor = .red
}
cell.Label.text = String(data[indexPath.row])
return cell
}
}
class CollectionViewCell: UICollectionViewCell {
#IBOutlet weak var Label: UILabel!
#IBOutlet weak var button: UIButton!
var callback : (() -> Void)?
#IBAction func buttonPressed(_ sender: UIButton) {
callback?()
}
}
I have CollectionView with CollectionViewCells that I switched. First I have this
After I get my secondCell with code
I use same sell with different methods to change text, but in first cell.textField as custom cocoapod library TKFormTextField and in second case I want to use simple UITextField. What enum and how should I use it?
here is my cell
class PhoneNumberCollectionViewCell: UICollectionViewCell, NiBLoadable {
#IBOutlet weak var phoneLabel: UILabel!
#IBOutlet weak var PhoneNumberTextField: UITextField!
#IBOutlet weak var SecurityLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
Decorator.decorate(self)
}
func setPhoneLabelText(text: String) {
phoneLabel.text = text
}
func setSecurityLabel(text: String) {
SecurityLabel.text = text
}
}
extension PhoneNumberCollectionViewCell {
fileprivate class Decorator {
static func decorate(_ cell: PhoneNumberCollectionViewCell) {
cell.phoneLabel.textColor = UIColor(red: 50.0/255.0, green: 50.0/255.0, blue: 50.0/255.0, alpha: 1.0)
cell.SecurityLabel.textColor = UIColor(red: 50.0/255.0, green: 50.0/255.0, blue: 50.0/255.0, alpha: 0.6)
cell.phoneLabel.font = UIFont(name: "OpenSans", size: 15)
cell.SecurityLabel.font = UIFont(name: "OpenSans", size: 12)
}
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let models = model[indexPath.row]
switch models {
case .phoneNumber:
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhoneNumberCollectionViewCell.name, for: indexPath) as? PhoneNumberCollectionViewCell {
cell.PhoneNumberTextField.text = self.phoneNumber
cell.setSecurityLabel(text: "_ALLYOURDATAISINSECUREDAREA")
cell.setPhoneLabelText(text: "_YOURPHONENUMBER")
return cell
}
case .confirmCode:
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhoneNumberCollectionViewCell.name, for: indexPath) as? PhoneNumberCollectionViewCell {
cell.PhoneNumberTextField.text = self.confirmCode
cell.setPhoneLabelText(text: "_ENTERCODEFROMSMS")
cell.setSecurityLabel(text: "_IFYOUDIDNTRECIEVETHESMS")
cell.PhoneNumberTextField.defaultTextAttributes.updateValue(5.0, forKey: NSAttributedString.Key(rawValue: NSAttributedString.Key.kern.rawValue))
return cell
}
}
return UICollectionViewCell.init()
}
You have more option to do this:
Create two different custom cell for the different options.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let models = model[indexPath.row]
switch models {
case .phoneNumber:
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FirstCustomCell.name, for: indexPath) as? FirstCustomCell {
cell.PhoneNumberTextField.text = self.phoneNumber
cell.setSecurityLabel(text: "_ALLYOURDATAISINSECUREDAREA")
cell.setPhoneLabelText(text: "_YOURPHONENUMBER")
return cell
}
case .confirmCode:
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SecondCustomCell.name, for: indexPath) as? SecondCustomCell {
cell.PhoneNumberTextField.text = self.confirmCode
cell.setPhoneLabelText(text: "_ENTERCODEFROMSMS")
cell.setSecurityLabel(text: "_IFYOUDIDNTRECIEVETHESMS")
cell.PhoneNumberTextField.defaultTextAttributes.updateValue(5.0, forKey: NSAttributedString.Key(rawValue: NSAttributedString.Key.kern.rawValue))
return cell
}
}
return UICollectionViewCell.init()
}
On the PhoneNumberCollectionViewCell create both of the textfields and set alphas to 0.
class PhoneNumberCollectionViewCell: UICollectionViewCell, NiBLoadable {
#IBOutlet weak var phoneLabel: UILabel!
#IBOutlet weak var PhoneNumberTextField: TKFormTextField!,
#IBOutlet weak var CodeFromSmsTextField: UITextField!
#IBOutlet weak var SecurityLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
Decorator.decorate(self)
PhoneNumberTextField.alpha = 0
CodeFromSmsTextField.alpha = 0
}
func setPhoneLabelText(text: String) {
phoneLabel.text = text
}
func setSecurityLabel(text: String) {
SecurityLabel.text = text
}
}
And after this, you can show what you need.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let models = model[indexPath.row]
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhoneNumberCollectionViewCell.name, for: indexPath) as? PhoneNumberCollectionViewCell else { return UICollectionViewCell() }
switch models {
case .phoneNumber:
cell.PhoneNumberTextField.text = self.phoneNumber
cell.setSecurityLabel(text: "_ALLYOURDATAISINSECUREDAREA")
cell.setPhoneLabelText(text: "_YOURPHONENUMBER")
cell.PhoneNumberTextField.alpha = 1
case .confirmCode:
cell.PhoneNumberTextField.text = self.confirmCode
cell.setPhoneLabelText(text: "_ENTERCODEFROMSMS")
cell.setSecurityLabel(text: "_IFYOUDIDNTRECIEVETHESMS")
cell.PhoneNumberTextField.defaultTextAttributes.updateValue(5.0, forKey: NSAttributedString.Key(rawValue: NSAttributedString.Key.kern.rawValue))
cell.CodeFromSmsTextField.alpha = 1
}
}
I'm having an issue when I'm selecting and deselecting the cell once, it works. But if I select the same cell again nothing happens, it doesn't trigger the didselect function. I also enabled multiple selection. Thank you for the help.
My code for CollectionViewCell:
class EventItemCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var txtLabel: UILabel!
#IBOutlet weak var imageCheck: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
public func toggleSelected() {
if (isSelected == false) {
//Hide check mark image.
self.imageCheck.image = UIImage(named: "success-1")
isSelected = true
}else{
//Show check mark image.
self.imageCheck.image = UIImage(named: "success-2")
isSelected = false
}
}
}
My code for the view controller:
import UIKit
class EventItemSelectionViewController: UIViewController {
#IBOutlet weak var collectionView: UICollectionView!
var items: [Item] = [Item(imageName: "vegetables"), Item(imageName: "cheers"), Item(imageName: "cocktail"), Item(imageName: "ice-cream"), Item(imageName: "soup"), Item(imageName: "steak")]
var itemsNames = ["Salades", "Boisson alcoolisée", "Boisson non-alcoolisée", "Dessert", "Entrée", "Viande"]
var itemsCheck = [UIImage(named: "success-2"), UIImage(named: "")]
var collectionViewFlowLayout: UICollectionViewFlowLayout!
let cellIdentifier = "ItemCollectionViewCell"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.edgesForExtendedLayout = UIRectEdge.bottom
setupCollectionView()
collectionView.allowsMultipleSelection = true
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
setupCollectionViewItemSize()
}
private func setupCollectionView(){
collectionView.delegate = self
collectionView.dataSource = self
let nib = UINib(nibName: "EventItemCollectionViewCell", bundle: nil)
collectionView.register(nib, forCellWithReuseIdentifier: cellIdentifier)
}
private func setupCollectionViewItemSize(){
if collectionViewFlowLayout == nil {
let numberOfItemPerRow: CGFloat = 2
let lineSpacing: CGFloat = 1
let interItemSpacing: CGFloat = 1
let width = (collectionView.frame.width - (numberOfItemPerRow - 1) * interItemSpacing) / numberOfItemPerRow
let height = width
collectionViewFlowLayout = UICollectionViewFlowLayout()
collectionViewFlowLayout.itemSize = CGSize(width: width, height: height)
collectionViewFlowLayout.sectionInset = UIEdgeInsets.zero
collectionViewFlowLayout.scrollDirection = .vertical
collectionViewFlowLayout.minimumLineSpacing = lineSpacing
collectionViewFlowLayout.minimumInteritemSpacing = interItemSpacing
collectionView.setCollectionViewLayout(collectionViewFlowLayout, animated: true)
}
}
}
extension EventItemSelectionViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCollectionViewCell", for: indexPath) as! EventItemCollectionViewCell
cell.imageView.image = UIImage(named: items[indexPath.item].imageName)
cell.txtLabel.text = itemsNames[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("\(indexPath)")
let cell = collectionView.cellForItem(at: indexPath) as? EventItemCollectionViewCell
cell?.isSelected = true
cell?.toggleSelected()
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as? EventItemCollectionViewCell
cell?.isSelected = false
cell?.toggleSelected()
}
}
Check this one
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCollectionViewCell", for: indexPath) as! EventItemCollectionViewCell
{
if !itemsNames.contains(indexPath.item) {
cell.backgroundColor = .red
self.itemsNames.append(indexPath.row)
} else {
cell.backgroundColor = .white
self.itemsNames.remove(object: indexPath.item)
}
}
}
But if I select the same cell again nothing happens
as you always set this to true inside didSelectItemAt
cell?.isSelected = true
cell?.toggleSelected()
var selectedArr = [Int]()
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForRow(at:indexPath) as! EventItemCollectionViewCell
if !selectedArr.contains(indexPath.item) {
cell.imageCheck.image = UIImage(named: "success-1")
self.selectedArr.append(indexPath.row)
} else {
cell.imageCheck.image = UIImage(named: "success-2")
self.selectedArr.remove(where:{ $0 == indexPath.item })
}
}
}
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.