Opening another screen by clicking on UICollectionViewCell - swift

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)

Related

How to get all collectionview cell index inside tableview cell using Protocol in Swift

I am using collectionview inside tableview cell. so when collectionview cell button is clicked then present viewcontroller i am using protocol..
code for tableviewcell and delegate:
protocol CustomCellDelegate: class {
func sharePressed(cell: ProposalTableVIewCell)
}
class ProposalTableVIewCell: UITableViewCell, UICollectionViewDelegate,UICollectionViewDataSource {
#IBOutlet weak var attetchmentsCollectionview: UICollectionView!
var delegate: CustomCellDelegate?
public var bidAttatchment: Array<Get_attachments>?
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return bidAttatchment?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AttatchmentCollectionViewCell", for: indexPath) as! AttatchmentCollectionViewCell
let attatchBid = bidAttatchment?[indexPath.item]
cell.attatchmentLbl.text = attatchBid?.filename
cell.openBtn.tag = indexPath.item
cell.openBtn.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)
return cell
}
#objc func connected(sender: UIButton){
delegate?.sharePressed(cell: self)
}
code for viewcontroller: when i press sharePressed getting only collectionview's first cell value.. how to get all cells value.. please do let me know
class ViewMyAppliedReqVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, CustomCellDelegate{
func sharePressed(cell: ProposalTableVIewCell) {
guard let index = tableView.indexPath(for: cell)?.row else { return }
let name = getBitDetails?.result?.bid?.get_attachments?[index].filename// always getting only first cell value
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ViewProposalTableVIewCell1", for: indexPath) as! ViewProposalTableVIewCell1
cell.bidAttatchment = getBitDetails?.result?.bid?.get_attachments
cell.delegate = self
cell.attetchmentsCollectionview.reloadData()
return cell
}
You are always getting same index because you are taking out index of "ProposalTableVIewCell" and this is tableView cell. And collectionView cells are in the same tableView cell.
Solution:
Take another parameter in protocol function like below for storing index of collection cell
protocol CustomCellDelegate: class {
func sharePressed(cell: ProposalTableVIewCell,collectionCellIndex:Int)
}
func sharePressed(cell: ProposalTableVIewCell, collectionCellIndex:Int) {
guard let index = tableView.indexPath(for: cell)?.row else { return }
let name = getBitDetails?.result?.bid?.get_attachments?[collectionCellIndex].filename// This will return index of collection cell
}
#objc func connected(sender: UIButton){
delegate?.sharePressed(cell: self,collectionCellIndex: sender.tag )
}

collectionView reloaddata inside TableView

I need to reloadData collectionView. Because I am append to array in function. I need to do reload data for this, but I get the error "Type of expression is ambiguous without more context". Data does not appear to be added because I did not reloadData. how can i use collectionView.reloadData? How can I reload data on TableView and CollectionView?
class denemeView: UIViewController, UITableViewDataSource, UITableViewDelegate {
var davetiyeKategori = [String]()
var davetiyeKatIsım = [String]()
var storedOffsets = [Int: CGFloat]()
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return kategoriIsımYeni[section]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return kategoriIsımYeni.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let tableViewCell = cell as? CategoryRow else { return }
tableViewCell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.row)
tableViewCell.collectionViewOffset = storedOffsets[indexPath.row] ?? 0
}
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let tableViewCell = cell as? CategoryRow else { return }
storedOffsets[indexPath.row] = tableViewCell.collectionViewOffset
}
func collectionReloadData(){
DispatchQueue.main.async(execute: {
self.collectionView.reloadData()
})
}
override func viewDidLoad() {
super.viewDidLoad()
davetiyeKategoriBul()
}
#objc func davetiyeKategoriBul(){
if let baslik = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] {
for review in baslik {
if let soru_baslik = review["ISIM"] as? String {
let s = String(describing: soru_baslik)
self.kategoriIsımYeni.append(s)
DispatchQueue.main.async {
// self.tableViewKategoriler.reloadData()
}} }}
extension denemeView: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return model[collectionView.tag].count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! anaSayfaCell
let rowValue = model[collectionView.tag][indexPath.item]
print("urlNew", rowValue)
let urlNew = URL(string: (rowValue))
cell.denemeImage.sd_setImage(with: urlNew)
// cell.backgroundColor = model[collectionView.tag][indexPath.item]
print("model[collectionView.tag][indexPath.item]", model[collectionView.tag][indexPath.item])
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("Collection view at row \(collectionView.tag) selected index path \(indexPath)")
}
}

To access Tableview cell in Button action

I want to delete tableview cell by clicking a button present in the same cell. But I am unable to access the cell in the button action function.
Please help me to Access this cell. My code is -
class MatchesViewController: UIViewController{
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "MatchingUsersTVCell") as? MatchingUsersTVCell else{
return UITableViewCell()
}
let likeUid = userIdArray[indexPath.row]
cell.heartBtn.tag = indexPath.row
cell.heartBtn.addTarget(self, action: #selector(userLikeButtonWasTappaed(sender:)), for: .touchUpInside)
}
#objc func userLikeButtonWasTappaed(sender: UIButton){
if let cell = sender.superview as? MatchingUsersTVCell{
CellAnimator.animate(cell: cell)
}
let tag = sender.tag
let userid = userIdArray[tag]
}
}
Try this code:
#objc func userLikeButtonWasTappaed(sender: UIButton){
guard let indexPath = tableView.indexPathForRow(at: sender.convert(sender.frame.origin, to: tableView)) else {
return
}
let cell = tableView.cellForRow(at: indexPath) as? MatchingUsersTVCell
}
And in your cellForRowAt function add the following code:
cell.yourBtn.tag = indexPath.row
cell.yourBtn.addTarget(self, action: #selector(userLikeButtonWasTappaed(sender:)), for: .touchUpInside)
I'd stay away from using tags, and instead implement protocol/delegate.
Using indexPath allows use of multiple sections, etc...
1) Create a protocol:
protocol MatchingUsersTVCellDelegate : class {
func didTapLikeButton(_ indexPath: IndexPath)
func didTapOtherButton(_ indexPath: IndexPath)
}
2) Create/Update your cell:
class MatchingUsersTVCell : UITableViewCell {
weak var delegate: MatchingUsersTVCellDelegate?
var indexPath: IndexPath!
// add target to your like button
func didTapLIkeButton(_ sender: UIButton) {
self.delegate?.didTapLikeButton(indexPath)
}
func didTapOtherButton() {
self.delegate?.didTapOtherButton(indexPath)
}
}
3) make sure your viewController conforms to the new delegate:
extension YourViewController: MatchingUsersTVCellDelegate {
func didTapLikeButton(_ indexPath: IndexPath) {
//Do something with the indexPath or indexPath.row
dataSource.remove(at: indexPath.row)
}
func didTapOtherButton(_ indexPath: IndexPath) {
//Do something else with the indexPath or indexPath.row
}
}
4) Set delegate and indexPath
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell...
cell.delegate = self
cell.indexPath = indexPath
return cell
}
Within MatchingUsersTVCell, add two properties, one named parentVC of type UIViewController and one named index of type Int:
class MatchingUsersTVCell: UITableViewCell {
var parentVC: UIViewController!
var index: Int!
...
}
Then, when creating each cell, set these two values appropriately:
class MatchesViewController: UIViewController, UITableViewDelegate, UITableViewDatasource {
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "MatchingUsersTVCell") as? MatchingUsersTVCell else {
return UITableViewCell()
}
cell.parentVC = self
cell.index = index
...
return cell
}
}
Now, you simply update your parentVC's tableView's data source and reload its data whenever the button is tapped:
class MatchingUsersTVCell: UITableViewCell {
...
#objc func userLikeButtonWasTappaed(sender: UIButton){
parentVC.userIdArray.remove(at: index)
parentVC.tableView.reloadData()
}
}
you can get it like this in your selector method
#objc func userLikeButtonWasTappaed(button:UIButton){
guard let indexPath = myTableView.indexPathForRow(at: button.convertPoint(button.frame.origin, toView: myTableView)) else {
print("Error: indexPath)")
return
}
print("indexPath.row: \(indexPath.row)")
}

UICollectionview - blink when move item

I want to reorder my cells in my UICollectionView. But when I drop my item, the "cellForItemAt" method is called and this will cause the cell to flash (See image below).
What should I do to avoid this behavior ?
Thank you in advance for your help.
class ViewController: UIViewController {
#IBOutlet weak var collectionView: UICollectionView!
private let cellIdentifier = "cell"
private let cells = [""]
private var longPressGesture: UILongPressGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongGesture(gesture:)))
collectionView.addGestureRecognizer(longPressGesture)
}
//Selectors
#objc func handleLongGesture(gesture: UILongPressGestureRecognizer) {
switch(gesture.state) {
case .began:
guard let selectedIndexPath = collectionView.indexPathForItem(at: gesture.location(in: collectionView)) else {
break
}
collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
case .changed:
collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
case .ended:
collectionView.endInteractiveMovement()
default:
collectionView.cancelInteractiveMovement()
}
}
}
// MARK: - UICollectionViewDataSource
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
return true
}
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 100)
}
}
You need to call endInteractiveMovement in perfomBatchUpdates.
But whenever endInteractiveMovement triggered, cellForRow called. So cell will be refreshed and new cell will added(check with random color extension). To secure that, you need to save selectedCell in variable. And return that cell when endInteractiveMovement called.
Declare currentCell in ViewController
var isEnded: Bool = true
var currentCell: UICollectionViewCell? = nil
Store selected cell in variable when gesture began & call endInteractiveMovement in performBatchUpdates.
So, your handleLongGesture func look like below:
//Selectors
#objc func handleLongGesture(gesture: UILongPressGestureRecognizer) {
switch(gesture.state) {
case .began:
guard let selectedIndexPath = collectionView.indexPathForItem(at: gesture.location(in: collectionView)) else {
break
}
isEnded = false
//store selected cell in currentCell variable
currentCell = collectionView.cellForItem(at: selectedIndexPath)
collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
case .changed:
collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
case .ended:
isEnded = true
collectionView.performBatchUpdates({
self.collectionView.endInteractiveMovement()
}) { (result) in
self.currentCell = nil
}
default:
isEnded = true
collectionView.cancelInteractiveMovement()
}
}
Also need to change cellForRow
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if currentCell != nil && isEnded {
return currentCell!
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath)
cell.backgroundColor = .random
return cell
}
}
TIP
Use random color extension for better testing
extension UIColor {
public class var random: UIColor {
return UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0)
}
}
EDIT
If you have multiple sections.
Lets take array of array
var data: [[String]] = [["1","2"],
["1","2","3","4","5","6","7"],
["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"]]
Then you need to maintain data when reordering
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
print("\(sourceIndexPath) -> \(destinationIndexPath)")
let movedItem = data[sourceIndexPath.section][sourceIndexPath.item]
data[sourceIndexPath.section].remove(at: sourceIndexPath.item)
data[destinationIndexPath.section].insert(movedItem, at: destinationIndexPath.item)
}
You can try to call
collectionView.reloadItems(at: [sourceIndexPath, destinationIndexPath])
right after all your updates (drag and drop animation) are done.
For example call it after performBatchUpdates. It will remove blinking.

How to set manual scroll position when collection view loads in 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