How to set manual scroll position when collection view loads in swift? - swift

I have the main table view where collection view is settled in table view section header because of the horizontal scroll view. when I click on collection view (row 1) table view reloads. but when I click on collection view row 5, it reloads the table view and shows the collection scroll position from the beginning. Please help me out to set the manual scroll position for collection view which is inside table view.
Here is code what I am using.
func numberOfSections(in tableView: UITableView) -> Int
{
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if section == 0
{
return 1
}
else
{
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
if indexPath.section == 0
{
let cell = tableView.dequeueReusableCell(withIdentifier: "banTableViewCell", for: indexPath) as! banTableViewCell
return cell
}
else
{
if chkVal == 0
{
let cell = tableView.dequeueReusableCell(withIdentifier: "onepageTableViewCell", for: indexPath) as! onepageTableViewCell
return cell
}
else if chkVal == 1
{
let cell = tableView.dequeueReusableCell(withIdentifier: "onepageTableViewCell", for: indexPath) as! onepageTableViewCell
return cell
}
else if chkVal == 2
{
let cell = tableView.dequeueReusableCell(withIdentifier: "onepageTableViewCell", for: indexPath) as! onepageTableViewCell
return cell
}
else if chkVal == 3
{
print("its cming gallery there")
let cell = tableView.dequeueReusableCell(withIdentifier: "containerTableViewCell", for: indexPath) as! containerTableViewCell
return cell
}
else
{
print("its cming calendar there")
let cell = tableView.dequeueReusableCell(withIdentifier: "galTableViewCell", for: indexPath) as! galTableViewCell
return cell
}
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
if section == 0
{
let view = UIView(frame: CGRect(x:0, y:0, width:0, height:0))
return view
}
else
{
let SegCell = tableView.dequeueReusableCell(withIdentifier: "segTableViewCell") as! segTableViewCell
SegCell.segcol.dataSource = self as UICollectionViewDataSource
SegCell.segcol.delegate = self as UICollectionViewDelegate
SegCell.segcol.isPagingEnabled = true
SegCell.segcol.isScrollEnabled = true
SegCell.segcol.showsHorizontalScrollIndicator = true
SegCell.segcol.register(UINib(nibName: "segCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "segCollectionViewCell")
// Initialization code
let indexPath = NSIndexPath(row: 3, section: 0)
SegCell.segcol.scrollToItem(at: indexPath as IndexPath, at: UICollectionViewScrollPosition.right, animated: false)
return SegCell
}
}
//Collection View Set
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "segCollectionViewCell", for: indexPath as IndexPath) as! segCollectionViewCell
if indexPath.row == 0
{
cell.TextSeg.text = "FITNESS REPORT CARD"
}
else if indexPath.row == 1
{
cell.TextSeg.text = "FITNESS STATS"
}
else if indexPath.row == 2
{
cell.TextSeg.text = "DIET & NUTRITION"
}
else if indexPath.row == 3
{
cell.TextSeg.text = "GALLERY"
}
else if indexPath.row == 4
{
cell.TextSeg.text = "CALENDAR"
}
return cell
}
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize
{
return CGSize(width:150, height:46)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
if indexPath.row == 0
{
tbl.reloadData()
}
else if indexPath.row == 1
{
tbl.reloadData()
}
else if indexPath.row == 2
{
tbl.reloadData()
}
else if indexPath.row == 3
{
tbl.reloadData()
}
else if indexPath.row == 4
{
tbl.reloadData()
}
}
It's not setting the scroll position in the collection view.
Thanks

Related

How to show AdCell for every three cells of table view in swift

I have to show Adcell for every three cells after. for that I have taken two prototype cells and designed adcell in one and normal cell in other
code: with my code only after first three rows AdCell showing and lost 3rd row from JobsCell from 4th row data showing
how to show Adcell for every cells and without losing JobsCell data. please guide
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return categoryData?.result?.categoryData?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var returnCell: UITableViewCell!
if indexPath.row == 3 {
returnCell = tableView.dequeueReusableCell(withIdentifier: "AdCell", for: indexPath) as! AdCell
}
else {
returnCell = tableView.dequeueReusableCell(withIdentifier: "JobsCell", for: indexPath) as! JobsCell
returnCell.selectionStyle = .none
}
return returnCell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
var count = categoryData?.result?.categoryData?.count ?? 0
return count + count / 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var returnCell: UITableViewCell!
if indexPath.row % 3 == 0 && indexPath.row != 0 {
returnCell = tableView.dequeueReusableCell(withIdentifier: "AdCell", for: indexPath) as! AdCell
}
else {
returnCell = tableView.dequeueReusableCell(withIdentifier: "JobsCell", for: indexPath) as! JobsCell
returnCell.selectionStyle = .none
}
return returnCell
}
The first problem: in your example func(numberOfItemsInSection) returns less rows than need. Therefore, to begin with, adding the missing cells.
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let n = categoryData?.result?.categoryData?.count ?? 0
//for example here 10 jobs
//3j 1a 3j 1a 3j 1a 1j(last) Here 3ads
//10/3 = 3(and 1)
//so will 11/3=3(2), then 12/3=4(0)
//So generic formula: num = j + j/3
let num = n + n/3 //n is Int so division rounds the number down
return num
}
Second problem: when adding an extra cell in indexPath, it gonna lost fourth job if using data[indexPath.row].
So it possible to create variable like "jumpDownNumber". It will save the step to the skipped indexPath.row number.
var jumpDownNumber = 0 //and reload it before tableView.reloadData()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var returnCell: UITableViewCell!
//after 3 jobCell is every fourth AD cell
if (indexPath.row+1) % 4 == 0 {
returnCell = tableView.dequeueReusableCell(withIdentifier: "AdCell", for: indexPath) as! AdCell
jumpDownNumber += 1
} else {
returnCell = tableView.dequeueReusableCell(withIdentifier: "JobsCell", for: indexPath) as! JobsCell
//here you can use data[indexPath.row-jumpDownNumber]
returnCell.selectionStyle = .none
}
return returnCell
}

UITableView not remembering selection when collapsing

I have a tableview with 3 collapsible sections. users can only select rows in section 3 and when they select it goes green. However, when this section is collapsed all the selections are forgotten and when I re-open the section, usually the first row is always green (though it shouldn't be). Sometimes, other sections end up being green too when they shouldn't - not sure what I've got wrong?
// Number of table sections
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
// Set the number of rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.expandedSectionHeaderNumber == section) {
// If markscheme, create the markscheme format
if (section == 2)
{
return self.markschemeRows.count
}
else
{
let arrayOfItems = self.sectionItems[section] as! NSArray
return arrayOfItems.count
}
} else {
return 0;
}
}
// Set titles for sections
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if (self.sectionNames.count != 0) {
return self.sectionNames[section] as? String
}
return ""
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44.0;
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
return 0;
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
//recast your view as a UITableViewHeaderFooterView
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.contentView.backgroundColor = UIColor.darkGray
header.textLabel?.textColor = UIColor.white
if let viewWithTag = self.view.viewWithTag(kHeaderSectionTag + section) {
viewWithTag.removeFromSuperview()
}
let headerFrame = self.view.frame.size
let theImageView = UIImageView(frame: CGRect(x: headerFrame.width - 32, y: 13, width: 18, height: 18));
theImageView.image = UIImage(named: "Chevron-Dn-Wht")
theImageView.tag = kHeaderSectionTag + section
header.addSubview(theImageView)
// make headers touchable
header.tag = section
let headerTapGesture = UITapGestureRecognizer()
headerTapGesture.addTarget(self, action: #selector(CaseViewController.sectionHeaderWasTouched(_:)))
header.addGestureRecognizer(headerTapGesture)
}
// Load the table data
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
let section = self.sectionItems[indexPath.section] as! NSArray
cell.textLabel?.textColor = UIColor.black
cell.selectionStyle = .none
//cell.backgroundColor = .white
// Get the data from different arrays depending on the section
if indexPath.section == 2 {
cell.textData?.text = markschemeRows[indexPath.row]
} else {
cell.textData?.text = section[indexPath.row] as! String
}
return cell
}
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if indexPath.section == 0{
if indexPath.row == 0{
return nil
}
}
else if indexPath.section == 1{
if indexPath.row == 0{
return nil
}
}
return indexPath
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
let cell = tableView.cellForRow(at: indexPath)
cell?.backgroundColor = .green
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cell = tableView.cellForRow(at: indexPath)
if (cell?.backgroundColor == .green)
{
cell?.backgroundColor = .white
}
}
// MARK: - Expand / Collapse Methods
#objc func sectionHeaderWasTouched(_ sender: UITapGestureRecognizer) {
let headerView = sender.view as! UITableViewHeaderFooterView
let section = headerView.tag
let eImageView = headerView.viewWithTag(kHeaderSectionTag + section) as? UIImageView
if (self.expandedSectionHeaderNumber == -1) {
self.expandedSectionHeaderNumber = section
tableViewExpandSection(section, imageView: eImageView!)
} else {
if (self.expandedSectionHeaderNumber == section) {
tableViewCollapeSection(section, imageView: eImageView!)
} else {
let cImageView = self.view.viewWithTag(kHeaderSectionTag + self.expandedSectionHeaderNumber) as? UIImageView
tableViewCollapeSection(self.expandedSectionHeaderNumber, imageView: cImageView!)
tableViewExpandSection(section, imageView: eImageView!)
}
}
}
func tableViewCollapeSection(_ section: Int, imageView: UIImageView) {
let sectionData = self.sectionItems[section] as! NSArray
self.expandedSectionHeaderNumber = -1;
if (sectionData.count == 0) {
return;
} else {
UIView.animate(withDuration: 0.4, animations: {
imageView.transform = CGAffineTransform(rotationAngle: (0.0 * CGFloat(Double.pi)) / 180.0)
})
var indexesPath = [IndexPath]()
// If markscheme, different number needed
if (section == 2)
{
for i in 0 ..< markschemeRows.count {
let index = IndexPath(row: i, section: section)
indexesPath.append(index)
}
}
else
{
for i in 0 ..< sectionData.count {
let index = IndexPath(row: i, section: section)
indexesPath.append(index)
}
}
self.tableView!.beginUpdates()
self.tableView!.deleteRows(at: indexesPath, with: UITableView.RowAnimation.fade)
self.tableView!.endUpdates()
}
}
func tableViewExpandSection(_ section: Int, imageView: UIImageView) {
let sectionData = self.sectionItems[section] as! NSArray
if (sectionData.count == 0) {
self.expandedSectionHeaderNumber = -1;
return;
} else {
UIView.animate(withDuration: 0.4, animations: {
imageView.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat(Double.pi)) / 180.0)
})
var indexesPath = [IndexPath]()
// If markscheme, create the markscheme format
if (section == 2)
{
for i in 0 ..< markschemeRows.count {
let index = IndexPath(row: i, section: section)
indexesPath.append(index)
}
}
else
{
for i in 0 ..< sectionData.count {
let index = IndexPath(row: i, section: section)
indexesPath.append(index)
}
}
self.expandedSectionHeaderNumber = section
self.tableView!.beginUpdates()
self.tableView!.insertRows(at: indexesPath, with: UITableView.RowAnimation.fade)
self.tableView!.endUpdates()
}
}
The key thing to understand here is that the Cells are Reused when you say
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
dequeueReusableCell basically reuses a previously loaded UITableViewCell and in your case you changed the background color of the cell to green
To get a better understanding of the concept consider reading some articles like this one on Reusing Cells
Changes in Code
What you should do considering the above in mind
var backgroundColors = [UIColor](repeating: UIColor.white, count: 10)
you have to save the state of the colors in a model (ideally you should make a custom struct)
now in cellForRowAt add this
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
.
.
cell.backgroundColor = backgroundColors[indexPath.row]
// **EDIT**
let cellShouldBeSelected = backgroundColors[indexPath.row] == .green
if cellShouldBeSelected {
tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
}
.
.
return cell
}
And your didSelectRowAt and didDeselectRowAt should update the model
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.backgroundColors[indexPath.row] = .green
tableView.reloadRows(at: [indexPath], with: .none)
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if (self.backgroundColors[indexPath.row] == .green) {
self.backgroundColors[indexPath.row] = .white
tableView.reloadRows(at: [indexPath], with: .none)
}
}
On second thought
Solution 2 (Recommended)
From you comments, i see you only need one selected cell at one time, assuming that keeping an array of backgroundColors is just a bad idea.
declare a int for the selected index
// -1 representing nothing is selected in the beginning
var selectedRow = -1
now your cellForRowAt will look like
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
.
.
if indexPath.section == 2, indexPath.row == self.selectedRow {
cell.backgroundColor = .green
} else {
cell.backgroundColor = .white
}
.
.
return cell
}
And your didSelectRowAt
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 2 {
self.selectedRow = indexPath.row
tableView.reloadSections([2], with: .automatic)
}
}
And now you can remove didDeselectRowAt completely

swift tableview change reloadData to insertRows

trying to change method to update the data, because with reloadData have lag
let oldIns = insertCounter
insertCounter += Int(INSERT_MESSAGES) // +40
var indexPaths = [IndexPath]()
for section in (oldIns..<insertCounter) {
indexPaths.append(IndexPath(row: 2, section: section))
}
tableView.beginUpdates()
tableView.insertRows(at: indexPaths, with: .automatic)
tableView.endUpdates()
but i have error
The number of sections contained in the table view after the update
(80) must be equal to the number of sections contained in the table
view before the update (40), plus or minus the number of sections
inserted or deleted (0 inserted, 0 deleted)
func numberOfSections(in tableView: UITableView) -> Int {
return min(insertCounter, Int(dbmessages.count))
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return RCMessages().sectionHeaderMargin
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return RCMessages().sectionFooterMargin
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.tintColor = UIColor.clear
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
view.tintColor = UIColor.clear
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if (indexPath.row == 0) {
return RCSectionHeaderCell.height(indexPath, messagesView: self)
}
if (indexPath.row == 1) {
return RCBubbleHeaderCell.height(indexPath, messagesView: self)
}
if (indexPath.row == 2) {
let rcmessage = self.rcmessage(indexPath)
if (rcmessage.type == RC_TYPE_STATUS) { return RCStatusCell.height(indexPath, messagesView: self) }
if (rcmessage.type == RC_TYPE_TEXT) { return RCTextMessageCell.height(indexPath, messagesView: self) }
}
if (indexPath.row == 3) {
return RCBubbleFooterCell.height(indexPath, messagesView: self)
}
if (indexPath.row == 4) {
return RCSectionFooterCell.height(indexPath, messagesView: self)
}
return 0
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath.row == 0) {
let cell = tableView.dequeueReusableCell(withIdentifier: "RCSectionHeaderCell", for: indexPath) as! RCSectionHeaderCell
cell.bindData(indexPath, messagesView: self)
return cell
}
if (indexPath.row == 1) {
let cell = tableView.dequeueReusableCell(withIdentifier: "RCBubbleHeaderCell", for: indexPath) as! RCBubbleHeaderCell
cell.bindData(indexPath, messagesView: self)
return cell
}
if (indexPath.row == 2) {
let rcmessage = self.rcmessage(indexPath)
if (rcmessage.type == RC_TYPE_STATUS) {
let cell = tableView.dequeueReusableCell(withIdentifier: "RCStatusCell", for: indexPath) as! RCStatusCell
cell.bindData(indexPath, messagesView: self)
return cell
}
if (rcmessage.type == RC_TYPE_TEXT) {
let cell = tableView.dequeueReusableCell(withIdentifier: "RCTextMessageCell", for: indexPath) as! RCTextMessageCell
cell.bindData(indexPath, messagesView: self)
let numSections = self.tableView.numberOfSections
if numSections == 1 {
updateTableContentInset()
}
return cell
}
}
if (indexPath.row == 3) {
let cell = tableView.dequeueReusableCell(withIdentifier: "RCBubbleFooterCell", for: indexPath) as! RCBubbleFooterCell
cell.bindData(indexPath, messagesView: self)
return cell
}
if (indexPath.row == 4) {
let cell = tableView.dequeueReusableCell(withIdentifier: "RCSectionFooterCell", for: indexPath) as! RCSectionFooterCell
cell.bindData(indexPath, messagesView: self)
return cell
}
return UITableViewCell()
}
How can i correct insert new row in tableview?
Before does like this
insertCounter += Int(INSERT_MESSAGES)
tableView.reloadData()
It's a pretty simple code line:
tableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .top)
This will insert the new row at the top of the table view. Then you would reload the data. This should fix the problem.

Opening another screen by clicking on UICollectionViewCell

I have a screen that contains a UITableView and inside some UICollectionViews.
I need to click on UICollectionViewCell and open the next screen, and send some information to this new screen. But I can not.
According to my structure "follows" does not work. I need some help to find another way to do this.
Code: - TableViewCell
class CategoriasTableViewCell: UITableViewCell {
var db: Firestore!
var categoriasArray = [Categorias]()
#IBOutlet weak var collectionView: UICollectionView!
#IBOutlet weak var labelTitleCategorias: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
collectionView.dataSource = self
collectionView.delegate = self
/*Firebase*/
let autenticacao = Auth.auth()
autenticacao.addStateDidChangeListener { (autenticacao, usuario) in
if let usuarioLogado = usuario {
} else {
//self.performSegue(withIdentifier: "checkEntrarSegue", sender: nil)
}
}
db = Firestore.firestore()
loadData()
}
func loadData() {
db.collection("Categories")
.addSnapshotListener { querySnapshot, error in
guard let documents = querySnapshot?.documents else {
print("Error fetching documents: \(error!)")
return
}
self.categoriasArray = querySnapshot!.documents.flatMap({Categorias(dictionary: $0.data())})
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
}
Code - TableView
class TabHomeViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
let autenticacao = Auth.auth()
autenticacao.addStateDidChangeListener { (autenticacao, usuario) in
if usuario == nil {
self.performSegue(withIdentifier: "logoutAutomatico", sender: nil)
//....
}
}
}
}
extension TabHomeViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellSlide", for: indexPath) as! SlideTableViewCell
return cell
} else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellCategorias", for: indexPath) as! CategoriasTableViewCell
//cell.collectionView.reloadData()
return cell
} else if indexPath.row == 2{
let cell = tableView.dequeueReusableCell(withIdentifier: "cellRecomendacoes", for: indexPath) as! RecomendacoesTableViewCell
return cell
} else if indexPath.row == 3 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellPromocoes", for: indexPath) as! PromocoesTableViewCell
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellFamosos", for: indexPath) as! FamososTableViewCell
return cell
}
}
/*func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == 1 {
if let cell = cell as? CategoriasTableViewCell {
cell.collectionView.reloadData()
print("Atualizando Collection1")
}
}
}*/
}
extension TabHomeViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.row {
case 0:
return 215
case 1:
return 200
case 2:
return 300
case 3:
return 400
case 4:
return 500
default:
return UITableViewAutomaticDimension
}
}
}
//COLLECTION CATEGORIAS
extension CategoriasTableViewCell: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return categoriasArray.count //Int(Constant.totalItem)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//set the image URL
let urlBase = categoriasArray[indexPath.row].foto_horizontal
let imageUrl = URL(string: urlBase)!
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BoxCollectionCategorias", for: indexPath) as! CellCategoriasCollectionViewCell
cell.labelNameCategoria.text = categoriasArray[indexPath.row].nome
cell.imageView.sd_setImage(with: imageUrl) { (image, erro, cache, url) in
// Here my code ...
}
return (cell)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("Click... \(categoriasArray[indexPath.row].uid)")
// Here I detect the click on the UICollectionViewCell
}
}
extension CategoriasTableViewCell: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 130)
}
}
I'm using an extension CategoriasTableViewCell: UICollectionViewDataSource {}, to edit the UICollectionView data
You can just create delegate for your TableViewCell
protocol CategoriasTableViewCellDelegate : class {
func categoryTapped(_ cell: CategoriasTableViewCell, categoriasID:Int)
}
class CategoriasTableViewCell: UITableViewCell {
weak var delegate : CategoriasTableViewCellDelegate?
}
And In CategoriasTableViewCell Extention
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if delegate != nil {
delegate?.categoryTapped(self, categoriasID: categoriasArray[indexPath.row].uid)
}
print("Click... \(categoriasArray[indexPath.row].uid)")
// Here I detect the click on the UICollectionViewCell
}
At your TabHomeViewController set cell.delegate = self
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellSlide", for: indexPath) as! SlideTableViewCell
return cell
} else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellCategorias", for: indexPath) as! CategoriasTableViewCell
//cell.collectionView.reloadData()
cell.delegate = self
return cell
} else if indexPath.row == 2{
let cell = tableView.dequeueReusableCell(withIdentifier: "cellRecomendacoes", for: indexPath) as! RecomendacoesTableViewCell
return cell
} else if indexPath.row == 3 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellPromocoes", for: indexPath) as! PromocoesTableViewCell
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellFamosos", for: indexPath) as! FamososTableViewCell
return cell
}
}
// now you can get Data in TabHomeViewController
extension TabHomeViewController:CategoriasTableViewCellDelegate {
func categoryTapped(_ cell: CategoriasTableViewCell, categoriasID:Int){
}
}
You need to trigger a segue to reach the other view, or present your new view on top of the current view (which I don't recommend unless you know what you are doing).
To pass your information from one view to another you have several options :
pass it through the segue (one to one)
use protocols & delegates (one to one)
use events & observers (one to many)
use a third class responsible for holding the current data (one to many)

Collection View is faulty when on ipad2?

I have a 3 collection views on a page. However when I run it on ipad two it doubles up like in the image below:
This is the faulty view
This is what it should look like and it does on iphone:
This is what it should look like
I have a feeling it has something to do with the constraints, but the code for the delegate is this:
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == prodCollectionView {
//print("There are \(prodImage.count) prodImage Items")
return prodImage.count
}
else if collectionView == revenueCollectionView {
//print("There are \(revImage.count) revImage items")
return revImage.count
}
else{
//print("There are \(accImage.count) accImage items")
return accImage.count
}
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let kWhateverHeightYouWant: CGFloat = 100
return CGSizeMake(collectionView.bounds.size.width, kWhateverHeightYouWant)
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if collectionView == prodCollectionView {
//print("collectionViewOne")
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("productCell", forIndexPath: indexPath) as! ImageCollectionViewCell
checkBegin[0] = indexPath.item
cell.images = self.prodImage[indexPath.item]
//collectionView.bounds = CGRect(x: <#T##CGFloat#>, y: <#T##CGFloat#>, width: <#T##CGFloat#>, height: <#T##CGFloat#>))
return cell
}
else if collectionView == revenueCollectionView{
//print("CollectionViewTwo")
//print(indexPath.item)
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("revCell", forIndexPath: indexPath) as! revenueImageCollectionViewCell
checkBegin[1] = indexPath.item
cell.images = self.revImage[indexPath.item]
return cell
}
else {
// print("CollectioNVieWThree")
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("accCell", forIndexPath: indexPath) as! AccessImageCollectionViewCell
checkBegin[2] = indexPath.item
cell.images = self.accImage[indexPath.item]
return cell
}
}