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
}
}
Related
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()
}
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.
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 implement flip animation in UICollectionViewCell. I have done it with 2 types of images. But I don't know how to implement it in array of images. The logic now:
but I want logic like this:
this is my code:
import UIKit
class CollectionViewCell: UICollectionViewCell {
#IBOutlet weak var coImage: UIImageView!
let cardBackTag = 0
let cardFrontTag = 1
var cardViews: (frontView: UIImageView, backView: UIImageView)?
var imgViewFront: UIImageView!
var imgViewBack: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
imgViewFront = self.createCardWithImage(imageName: "1", tag: self.cardFrontTag)
imgViewBack = self.createCardWithImage(imageName: "2", tag: self.cardBackTag)
cardViews = (frontView: imgViewFront, backView: imgViewBack)
contentView.addSubview(imgViewBack)
}
private func createCardWithImage(imageName: String, tag: Int) -> UIImageView {
let newCardImageView = UIImageView(frame: self.frame)
newCardImageView.image = UIImage(named: imageName)
newCardImageView.tag = tag
return newCardImageView
}
func flipCardAnimation(indexPath: IndexPath) {
if (imgViewBack.superview != nil) {
cardViews = (frontView: imgViewFront, backView: imgViewBack)
}else{
cardViews = (frontView: imgViewBack, backView: imgViewFront)
}
let transitionOptions = UIViewAnimationOptions.transitionFlipFromLeft
UIView.transition(with: self.contentView, duration: 1.0, options: transitionOptions, animations: {
self.cardViews!.backView.removeFromSuperview()
self.contentView.addSubview(self.cardViews!.frontView)
}, completion: { finished in
print(indexPath)
})
}
}
and
import UIKit
class CollectionViewController: UICollectionViewController {
var reuseIdentifier = "CollectionViewCell"
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView!.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
}
// MARK: UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 8
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! CollectionViewCell
cell.flipCardAnimation(indexPath: indexPath)
}
}
Please, help me to implement this logic! Thank you a lot!!
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.