didSelectItemAt() is not loading my viewController - ios

First viewController
import UIKit
class photosCollectionViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
#IBOutlet weak var photoCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
photoCollectionView.delegate = self
photoCollectionView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
var photosArray = PhotoClass(Name:["Dog","Cat","Lion","Tiger"])
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photosArray.Name.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let photocell = photoCollectionView.dequeueReusableCell(withReuseIdentifier: "photosCell", for: indexPath) as! photoscollectionCell
//photocell.backgroundColor = UIColor.blue
photocell.cellImage.image = UIImage(named: photosArray.Name[indexPath.row])
photocell.cellLabel.text = photosArray.Name[indexPath.row]
return photocell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("Something")
let vc = self.storyboard?.instantiateViewController(withIdentifier: "photosDetails") as! detailsCollectionViewController
// vc.descriptionLabel.text = "Animals"
}
}
didSelectItemAt() is not loading my detailsCollectionViewController,but while i am selecting the cell it's calling .so where am i doing wrong ?

you can write this if you want to push :
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("Something")
let vc = self.storyboard?.instantiateViewController(withIdentifier: "photosDetails") as! detailsCollectionViewController
// vc.descriptionLabel.text = "Animals"
self.navigationController?.pushViewController(vc, animated: true)
}
It may helps to you.Thank you

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("Something")
let vc = self.storyboard?.instantiateViewController(withIdentifier: "photosDetails") as! detailsCollectionViewController
// vc.descriptionLabel.text = "Animals"
present(vc, animated: true)
}

Related

How to pass collectionview cells index value to nextviewcontroller(using push navigation) in swift

I am using collectionview in tableview cell,
i need to pass selected collectionview cells value to next viewcontroller, how?
code: here is the code for tableview and collectionview cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryNewTableCell", for: indexPath) as! CategoryNewTableCell
let indexData = self.activeCategories?[indexPath.row]
cell.selectionStyle = .none
cell.catNameLbl.text = indexData?.details?.first?.title
cell.subCategories = indexData?.sub_categories
cell.clcSeller.reloadData()
}
class CategoryNewTableCell: UITableViewCell,UICollectionViewDelegate,UICollectionViewDataSource{
#IBOutlet weak var clcSeller: UICollectionView!
public var subCategories : Array<Sub_categories>?
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return subCategories?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SubCatCollectionCell", for: indexPath) as! SubCatCollectionCell
let subCategory = self.subCategories?[indexPath.item]
cell.lblTitle.text = langType == .en ? subCategory?.details?.first?.title : subCategory?.details?[1].title
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let vc = StoryBoard.main.instantiateViewController(withIdentifier: "SearchResultVC") as! SearchResultVC
vc.subCatId = sub_categories?[indexPath.row].slug ?? ""
self.navigationController?.pushViewController(vc, animated: true)
}
}
here if i use didSelectItemAt for collectionview to send its selected cell value to next view controller
error:
Value of type 'CategoryNewTableCell' has no member 'navigationController'
if i give button action in main class then able to push but value is not going
class CategoryNewVC: UIViewController {
#IBAction func didselectcollectionviewBTn(_ sender: UIButton) {
let vc = StoryBoard.main.instantiateViewController(withIdentifier: "SearchResultVC") as! SearchResultVC
vc.subCatId = //here how to pass value
self.navigationController?.pushViewController(vc, animated: true)
}
}
here how to pass selected collectionview cells value to SearchResultVC please do help
EDIT
according to below answer i have added: still didSelectItemAt not called, why plz do help
class CategoryNewTableCell: UITableViewCell,UICollectionViewDelegate,UICollectionViewDataSource{
override func awakeFromNib() {
super.awakeFromNib()
self.clcSeller.delegate = self
self.clcSeller.dataSource = self
//
You can use protocol to send data to your nextviewcontroller.
protocol CategorySelectionDelegate {
func get(category: Sub_categories)
}
Declare the delegate in your CategoryNewTableCell and use it in didSelectItemAt method of your collectionviewcell like below:
class CategoryNewTableCell:
UITableViewCell,UICollectionViewDelegate,UICollectionViewDataSource{
#IBOutlet weak var clcSeller: UICollectionView!
public var subCategories : Array<Sub_categories>?
var delegate: CategorySelectionDelegate?
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return subCategories?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SubCatCollectionCell", for: indexPath) as! SubCatCollectionCell
let subCategory = self.subCategories?[indexPath.item]
cell.lblTitle.text = langType == .en ? subCategory?.details?.first?.title : subCategory?.details?[1].title
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.get(category: sub_categories?[indexPath.row])
}
}
Adopt the protocol in the receiving class
class CategoryNewVC: UIViewController, CategorySelectionDelegate {
func get(category: Sub_categories) {
let vc = StoryBoard.main.instantiateViewController(withIdentifier: "SearchResultVC") as! SearchResultVC
vc.subCatId = category.slug ?? ""
self.navigationController?.pushViewController(vc, animated: true)
}
}
Declare a callback in the tableViewCell subclass.
class CategoryNewTableCell: UITableViewCell {
var onSelectSubcategory: ((_ subcategoryID: String) -> Void)?
}
Assign this callback in your cellForRow like this.
cell.subCategories = indexData?.sub_categories
cell.onSelectSubcategory = { [weak self] (subcategoryID) in
let vc = StoryBoard.main.instantiateViewController(withIdentifier: "SearchResultVC") as! SearchResultVC
vc.subCatId = subcategoryID
self?.navigationController?.pushViewController(vc, animated: true)
}
Invoke this callback from collectionView didSelectItem like this.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let subcategoryID = sub_categories?[indexPath.item].slug ?? ""
self.onSelectSubcategory?(subcategoryID)
}

want to add a collectionView inside tableView by downloading data from firebase to show . ios App Swift

want to add a UICollectionView inside UITableView by downloading data from firebase to show
Now I'm done with the interface part, but I'm stuck in the problem, can't bring data from firebase to show in the UICollectionView.
I can't run collectionView.reloadData() because the UICollectionView is different in class, how should I fix it?
func showImageRewardData(rewardID:String) {
let databaseRef = Database.database().reference().child("reward").child(rewardID).child("rewardImage")
databaseRef.observe(DataEventType.value, with: { (Snapshot) in
if Snapshot.childrenCount>0{
self.rewardDataArr.removeAll()
for rewardImage in Snapshot.children.allObjects as! [DataSnapshot]{
let rewardObject = rewardImage.value as? [String: AnyObject]
if(rewardObject?["imageURL"] != nil){
let imageUrl = rewardObject?["imageURL"]
let Data = rewardDetailClass(rewardImage: imageUrl as? String)
self.rewardDataArr.insert(Data, at: 0)
}
YOURVIEWCONTROLLER.SWIFT
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let CellIdentifier: String = "Cell_NotesList"
var cell: Cell_NotesList? = (tableView.dequeueReusableCell(withIdentifier: CellIdentifier) as? Cell_NotesList)
if cell == nil {
let topLevelObjects: [Any] = Bundle.main.loadNibNamed("Cell_NotesList", owner: nil, options: nil)!
cell = (topLevelObjects[0] as? Cell_NotesList)
cell?.selectionStyle = .none
}
cell?.reloadCollectionView(arr: arrofofthumbImages)
return cell!
}
YourCell.SWIFT
class Cell_NotesList: UITableViewCell {
var imagesArr = NSMutableArray()
override func awakeFromNib() {
collectionView.register(UINib.init(nibName: "cell_ImageCollection", bundle: nil), forCellWithReuseIdentifier: "cell_ImageCollection")
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
extension Cell_NotesList : UICollectionViewDataSource {
func reloadCollectionView(arr:NSMutableArray) {
imagesArr = arr
collectionView.reloadData()
self.layoutIfNeeded()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imagesArr.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : cell_ImageCollection? = collectionView.dequeueReusableCell(withReuseIdentifier: "cell_ImageCollection", for: indexPath) as? cell_ImageCollection
//YOUR CODE HERE
return cell!
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
}
extension Cell_NotesList : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 120.0, height: 120.0)
}
}
extension UICollectionViewCell {
var indexPath: IndexPath? {
return (superview as? UICollectionView)?.indexPath(for: self)
}
}
In class that extends UICollectionView, put one setter method like
func setData(data: String){
// Update your cell view here like
Label.text = data
}

CollectionView issue - Swift

I make music player using collectionView. I want to when selected collectionView like radio button. If another cell is selected, the selected cell should not be selected. but is not working.
I dont want multi selection. : https://i.stack.imgur.com/ATj3J.png
How do I work? TT I need your help. thx.
this my code.
import UIKit
class PracticeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var homeClassInPrac = HomeViewController()
var songPlayOff = UIImage(named: "play")
var songPlayOn = UIImage(named: "iconStop")
var buttonCounter = [Int]()
var freqNameList = ["Delta 1","Theta 1","Alpha 1","Beta 1","Delta 2","Theta 2","Alpha 2","Beta 2","Delta 3","Theta 3","Alpha 3","Beta 3","Delta 4","Theta 4","Alpha 4","Beta 4"]
#IBOutlet var practiceCollection: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
practiceCollection.delegate = self
practiceCollection.dataSource = self
self.practiceCollection.allowsMultipleSelection = false
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
self.practiceCollection.reloadData()
return freqNameList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:PracticeCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "pracCell", for: indexPath) as! PracticeCollectionViewCell
cell.pracImgView.image = songPlayOff
cell.pracLabel.text = freqNameList[indexPath.row]
if buttonCounter.contains(indexPath.row){
cell.pracImgView.image = songPlayOn
}
else{
cell.pracImgView.image = songPlayOff
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if buttonCounter.contains(indexPath.row){
let index = buttonCounter.index(of: indexPath.row)
buttonCounter.remove(at: index!)
self.practiceCollection.reloadData()
homeClassInPrac.audioPlayer2.stop()
}
else{
buttonCounter.removeAll()
buttonCounter.append(indexPath.row)
self.practiceCollection.reloadData()
let buttonInt = buttonCounter[0]
homeClassInPrac.playSound2(freqName: freqNameList[buttonInt])
}
print("Select\(buttonCounter)")
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
print("Deselect\(buttonCounter)")
let index = buttonCounter.index(of: indexPath.row)
buttonCounter.remove(at: index!)
self.practiceCollection.reloadData()
print("Deselect\(buttonCounter)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
I think problem is you are reloading collectionView in numberOfItems method
so Just remove
self.practiceCollection.reloadData()
Change buttonCounter to Array of Bool with equal count to freqNameList
var buttonCounter : Array<Bool> = [false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false]
In cellForItem method use :
if buttonCounter[indexPath.row]{
cell.pracImgView.image = songPlayOn
}
else{
cell.pracImgView.image = songPlayOff
}
In didSelectItem use :
buttonCounter[indexPath.row] = true
homeClassInPrac.playSound2(freqName: freqNameList[buttonInt])
self.practiceCollection.reloadData()
In didDeselectItem use :
buttonCounter[indexPath.row] = false
self.practiceCollection.reloadData()

Swift open new UIViewController

I'm trying to open new UIViewController when I click on an item inside UICollectionView, but using this code my app crashes and Xcode and simulator restarts so I can't even see where is the problem.
import UIKit
class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.register(CustomCell.self, forCellWithReuseIdentifier: "cellId")
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! CustomCell
cell.imageViewGame.image = UIImage(named: imageArray[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width / 2, height: view.frame.width / 2)
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
performSegue(withIdentifier: "postController", sender: title[indexPath.row])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "postController" {
let postController = segue.destination as! PostController
postController.title = sender as! String
}
}
}
Does anyone know from this code why my app crashes? If it's important, I'm not using storyboard.
Try this:
Make you don't forgot to declare postController identifier in your segue
You just can present it modally with:
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let postController = PostController()
postController.title = title[indexPath.row]
present(postController, animated: true, completion: nil)
}

How can I check if the core data is empty?

I am using core data to populate a collection view. Now i want to check if it is empty or not. I want to do additional stuff if it is empty. How can I achieve that?
if myJokes.isEmpty == true {
noFavorites.isHidden = false
}
I have tried to check it likes this but it did not work:
class ViewController2: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource {
var myJokes : [MyJokes] = []
override func viewDidLoad() {
super.viewDidLoad()
getData()
myCollectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return myJokes.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell2
if myJokes.isEmpty == true {
noFavorites.isHidden = false
}
cell.backView.layer.cornerRadius = 10
let task = myJokes[indexPath.row]
cell.textLabel.text = task.favoriteJokes!
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: myCollectionView.frame.width, height: 58)
}
func getData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do {
myJokes = try context.fetch(MyJokes.fetchRequest())
} catch {}
}
#IBAction func menuBtnPressed(_ sender: Any) {
if menuShowing {
menuConstraint.constant = -171
UIView.animate(withDuration: 0.4, animations: {
self.view.layoutIfNeeded()
})
}

Resources