Connect UITableView cell to another UITableView - uitableview

I am stucked with my project (written in Swift)
I have a UITableView, with a string which provide ten categories in the table.
The thing that I wanna do, is to select one of these categories touching it, and open a secondTableView with other categories. And, when you press on the secondTableView, open the description of that category.
This is my code, this works to have the first UITableView, but when touching nothing happens.
Now I'd like, for example, when I click "Most important places", it open another tableView with, for example, Empire State Building, Statue of Liberty, and when touching Empire State Building, open a Description page.
import UIKit
class Categories: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tableView: UITableView!
var MainCategories: [String] = ["Most important places", "Monuments", "Nature", "Churches", "Museums", "Streets", "Zones", "Weather", "Events", "Favourites"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.MainCategories.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel?.text = self.MainCategories[indexPath.row]
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
}
}
What can I do? And in the storyboard?
Thanks you very much!

So far you have done nothing in didSelectRowAtIndexPath for the second UITableView, it would be easy for you to make use of another viewcontroller which contains the second uitableview and then a third viewcontroller for details.
But if you still want to have 2 uitableviews within same viewcontroller then please follow these steps to achieve the required result.
add another tableview and set its datasource and delegate
you have to add an if-else condition to differntiate between 2 tablieview in delegate and datasource methods, e.g. numberOfRowsInSection, cellForRowAtIndexPath, didSelectRowAtIndexPath, below is an example of the code if you use 2 uitableviews in one uiviewcontroller. you have to do this if-else for other delegate and datasource mehtos as well.
func tableView(tableView: UITableView, numberOfRowsInSection section:Int)->Int {
if tableview == self.tableView {
return self.MainCategories.count
}
else if tableView == subCategoryTableView {
return self.SubCategories.count
}
}
Hope it helps!

I have changed your code, hope this helps
import UIKit
class Categories: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tableView: UITableView!
**var selectedCategoryId = -1**
var MainCategories: [String] = ["Most important places", "Monuments", "Nature", "Churches", "Museums", "Streets", "Zones", "Weather", "Events", "Favourites"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.MainCategories.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel?.text = self.MainCategories[indexPath.row]
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
**selectedCategoryId = indexPath.row**
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
let vc = segue.destinationViewController as YOUR_SECOND_VIEW_CONTROLLER
vc.catId = selectedCategoryId
}
}

Related

No information is showing in my tableview inside a viewController

I have set up my table view to be filled form two arrays. I did this successfully when it was just in a tableview but not that I put it in a view controller none of the information is being displayed. I don't know what I did wrong I set up the viewController just like I did with the tableviewcontroller.
What should happen is that a row will be created and filled in with the information and continue this until all the data has been filled in.
The problem is that none of the data is showing up. I don't know what I am missing here. Any help would be appreciated.
Here is what I have;
class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var titleDate = ["Apple", "Apricot", "Banana", "Kiwi" , "Juniperberry" , "GhostBusteres"]
var descriptionDate = ["One", "Two", "Three", "4", "5", "6"]
#IBOutlet weak var myTableView: UITableView!
// MARK: - UIViewController lifecycle
override func viewDidLoad() {
super.viewDidLoad()
myTableView.editing = true
}
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titleDate.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Coupon", forIndexPath: indexPath) as! CouponTableViewCell
cell.couponTitle.text = titleDate[indexPath.row]
cell.couponDescription.text = descriptionDate[indexPath.row]
cell.couponAnother.text = "Like a bloody storm"
return cell
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return .None
}
func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
let movedObject = self.titleDate[sourceIndexPath.row]
titleDate.removeAtIndex(sourceIndexPath.row)
titleDate.insert(movedObject, atIndex: destinationIndexPath.row)
descriptionDate.removeAtIndex(sourceIndexPath.row)
descriptionDate.insert(movedObject, atIndex: destinationIndexPath.row)
NSLog("%#", "\(sourceIndexPath.row) => \(destinationIndexPath.row) \(titleDate)")
// To check for correctness enable: self.tableView.reloadData()
}
}
And I also have the cell class that links the labels to the variables and that also works.
Thank you for any help with this.
You need to set the UITableView dataSource and delegate.
When you were using the UITableViewController, the dataSource and delegate were already set.
See UITableView - Managing the Delegate and the Data Source documentation.

Custom TableViewCell Swift

Here is the code from my custom cell class:
import UIKit
class CustomOrderTableViewCell: UITableViewCell {
#IBOutlet var MealName: UILabel!
#IBOutlet var MealPrice: UILabel!
#IBOutlet var MealDescription: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
#IBAction func deleteMeal(sender: AnyObject) {
}
}
Here are the table view related functions:
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mealArray.orderedMeals.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("in")
var cell = tableView.dequeueReusableCellWithIdentifier("orderCell", forIndexPath: indexPath) as! CustomOrderTableViewCell
cell.MealName.text = mealArray.orderedMeals[indexPath.row].mealName
cell.MealDescription.text = mealArray.orderedMeals[indexPath.row].mealDescription
let price = NSString(format: "%.2f", mealArray.orderedMeals[indexPath.row].mealPrice) as String
cell.MealPrice.text = "R" + price
return cell
}
The problem is that nothing gets displayed in the table view and func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell is never called.
Any solutions? Thanks
If func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell is never called that means you have not connected your UITableViewDataSource in IB correctly. Make sure that you connect the dataSource property with your ViewController. Also check that all classes are set for your ViewController, TableView and the Cell itself as this another common mistake.

not calling didSelectRowAtIndexPath method in Tableview

I have embedded UITabbar in UIViewController and then I put some UITabbarItems in my UITabbar. I also created another UIViewController with UITableView embedded in it.
I have linked one of the UITabbarItem with this newly created UIViewController(with UITableView in it).
When I run the program and tap on that UITabbarItem it shows a table view but when I select any row of table, the data displaying in UITableView disappears.
I then debug the code and found that didSelectRowAtIndexPath method didn't call.
I searched on the internet and find this but cannot understand it well.
I tried by implementing both types of tableViews (UITableViewController,UIViewController with UITableView in it) but still same problem.
I am stuck here. Anyone please help me. How to get resolve this issue.
I will be very Thankful to you.
Here is my swift code
import UIKit
class DashboardViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var selectedIndexPathForCheckMark:NSIndexPath?
var items: [String] = ["We", "Heart", "Swift"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("MyCell")!UITableViewCell
cell.textLabel?.text = self.items[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
selectedIndexPathForCheckMark = indexPath
tableView.reloadData()
}
here are its snapshots
Second UITabbarItem from right implements UITableView
Follow Steps:
1. Take A view controller and add tableview.
2. set outlet with MytabelView
3. set Datasource and delegate of tableview to ViewController
4. and put the following code in ViewController class
5. Take a custom tableview cell with name MyCell having cell identifier "MyCellid"
6. Create swift file with name MyCell, make it subclass of UITableViewCell
7. Choose custom cell and assign it class to MyCell.
I think Its done
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
#IBOutlet weak var MytableView: UITableView!
var items: [String] = ["We", "Heart", "Swift"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.MytableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "MyCellid")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.MytableView.dequeueReusableCellWithIdentifier("MyCellid")! as UITableViewCell
cell.textLabel?.text = self.items[indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
}
}

Why cellForRowAtIndex doesn't run at all?

I've added TableView to my controller and created custom UITableViewCell. Later, I've tried to run this code:
func tableView(educationTableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> educationCell {
let cell:educationCell = educationTableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! educationCell
print("TableView runs")
return cell
}
but I do not get my print in logs TableView runs. I do not understand what happens and why it doesn't run. Who knows, why this problem appears?
I read other answers in SO, but noone helps =/
need the return value of numberOfRowsInSection greater than 0
Just make sure you have implemented proper DataSource and Delegate for controller, number of rows is greater then 0
import UIKit
class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var items: [String] = ["We", "Heart", "Swift"]
#IBOutlet var tableView: UITableView! //hook this to your storyboard tableview
// MARK: - Controller life cycle stack
override func viewDidLoad() {
super.viewDidLoad()
//confirm table's delegate and data source programmatically
tableView.delegate = self;
tableView.dataSource = self;
}
//table view delegate and data source methods
func tableView(tableView:UITableView, numberOfRowsInSection section:Int) -> Int
{
//number of rows must be greater then 0 to get called "CellForRowAtIndex"
return self.items.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! CraditCardCell
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
print("You selected cell");
}
}
One reason could be because you modified the return type to educationCell, instdead of the standard UITableViewCell. Try changing that.

How do I activate a segue from a tableView where the datasource is from another swift file?

I have a tableView in my ViewController, the datasource for this table is from another swift file: DataSource.swift. This is the code of the datasource file:
import Foundation
import UIKit
class Datasource: NSData, UITableViewDataSource, UITableViewDelegate {
let itemsArray = ["Item 1","Item 2","Item 3","Item 4"]
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemsArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier:"test")
cell.textLabel!.text = self.itemsArray[indexPath.row]
return cell
}
}
I tried adding this code:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("mainToDetail", sender: self)
}
But it gave me an error, I also tried this code and it didn't work as well:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
ViewController.performSegueWithIdentifier("mainToDetail", sender: ViewController)
}
I want to add a functionality where when I click a row in the table, a segue from the ViewController is activated to show the DetailViewController.
Please help!
You can achieve this in many ways. For example,
hold reference of ViewController in Datasource's property
Passing closure
Delegate Pattern
But using delegate pattern is my preference.
First, you need to create DatasourceDelegate protocol.
protocol DatasourceDelegate: class{
func didSelectGoToMainMenu( datasource datasource: Datasource)
}
Second, In Datasource class, you will have a DatasourceDelegate object. Like this
class Datasource: NSObject,UITableViewDataSource,UITableViewDelegate{
//...
weak var delegate: DatasourceDelegate?
//...
}
and in tableView(_ :didSelectRowAtIndexPath:). It will call DatasourceDelegate function. Like this
extension Datasource: UITableViewDelegate{
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
delegate?.didSelectGoToMainMenu(datasource: self)
}
}
Finally, In your seperated ViewController class, You set the view controller to conform DatasourceDelegate protocol. Like this
class myViewController: UIViewController, DatasourceDelegate{
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
////////
let dataSource = Datasource()
dataSource.delegate = self
tableView.dataSource = dataSource
tableView.delegate = dataSource
}
// this function will be called when someone select a row
func didSelectGoToMainMenu(datasource datasource: Datasource) {
performSegueWithIdentifier("mainToDetail", sender: self)
}
}

Resources