UITableView is not showing up on physical device deployment - ios

I created a UITableView and fed it some data using code.
While running the application on Xcode simulator it works fine but when I deploy it on physical device, the UITableView is not visible.
Image - 1 (Simulator)
Image - 2 (Device)
Below is my Code:
import UIKit
class OTCMedicines: UIViewController, UITableViewDelegate, UITableViewDataSource{
#IBOutlet weak var tableView: UITableView!
struct Med {
var name:String
var detail:String
var imageName:String
var image: UIImage {
get {
return UIImage(named: imageName)!
}
}
}
var data:[Med]=[Med]()
override func viewDidLoad() {
super.viewDidLoad()
print("OTC Loaded")
data.append(Med(name:"Nimprex P",detail:"Fever and Painkiller",imageName:"db"))
data.append(Med(name:"Cozi Plus",detail:"Cold and Fever",imageName:"db"))
data.append(Med(name:"Combiflam",detail:"Headach and Painkiller",imageName:"db"))
data.append(Med(name:"Flexon",detail:"Muscle Painkiller",imageName:"db"))
data.append(Med(name:"Avil",detail:"Antibiotic",imageName:"db"))
data.append(Med(name:"Cetirizine",detail:"Antibiotic and Allergy",imageName:"db"))
data.append(Med(name:"LIV 52",detail:"Lever Problems",imageName:"db"))
data.append(Med(name:"Perinorm",detail:"Stomach-ach and Puke",imageName:"db"))
data.append(Med(name:"Edicone Plus",detail:"Fever and Cold",imageName:"db"))
data.append(Med(name:"L-Hist Mont",detail:"Peanut Allergies",imageName:"db"))
tableView.delegate = self
tableView.dataSource = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MedicineCell") as! OTCMedCell!
let medView = data[indexPath.row]
print("OTC Table Cell Loaded")
cell.medName.text = medView.name
cell.medImage.image = medView.image
cell.medDetail.text = medView.detail
return cell
}
// MARK: UITableViewDelegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "OTCMedPush" {
if let destination = segue.destinationViewController as? OTCMedicineDetail {
if let medIndex = tableView.indexPathForSelectedRow?.row {
destination.medicineValue = data[medIndex].name
}
}
}
}
}
Both simulator and iPhone are model 5s, running on iOS 9.2

I believe you need to reload the table after you added all the elements in viewDidLoad.
self.UITableView.reloadData()

Seems you must insert these lines in viewDidLoad:
self.tableView.registerNib(UINib(nibName: "OTCMedCell", bundle:nil), forCellReuseIdentifier: "MedicineCell")
self.tableView.reloadData()
Also, in your cellForRowAtIndexPath modify your line:
let cell = tableView.dequeueReusableCellWithIdentifier("MedicineCell") as! OTCMedCell!
with:
let cellIdentifier : String! = "MedicineCell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? OTCMedCell!
if cell == nil {
cell = OTCMedCell(style: UITableViewCellStyle.Default, reuseIdentifier: (cellIdentifier))
}

Related

UiTableView to UiTableView to UiViewcontroller swift

I am new here and to coding and I need some help with a project that I'm currently stuck on.
I have built an app containing UITableView the first displays body areas (Gastro, cardio, respiratory, etc), the second displays more detailed features on the first (in gastro the table will display stomach, small intestine, colon, etc) and then the the UIViewController will have the more detailed info on the stomach etc.
I have this working all ok but one problem has arose. The UIViewController, regardless of which option is selected in the first table, displays the same info, i.e I get results for gastro even after selecting cardio etc.
Below is my code. I hope someone could help with this. I would really appreciate it!
import UIKit
class Chapters: UITableViewController {
var ChaptersArray = [String]()
var SubchaptersArray = [secondTable]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// chapter names
ChaptersArray = ["Gastrointestinal","Cardiovascular","Respiratory","Central Nervous System", "Infections"]
// subcharpter names
SubchaptersArray = [secondTable(SecondTitle: ["Gas1", "Gas2", "Gas3", "Gas4"]),
secondTable(SecondTitle: ["Card1", "Card2", "Card3", "Card4"]),
secondTable(SecondTitle: ["Res1", "Res2", "Res3", "Res4"])]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableview: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell!
cell.textLabel?.text = ChaptersArray[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ChaptersArray.count
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let indexPath: NSIndexPath = self.tableView.indexPathForSelectedRow!
let destViewController = segue.destinationViewController as! Subchapters
var secondTableArrayTwo : secondTable
secondTableArrayTwo = SubchaptersArray[indexPath.row]
destViewController.SubChaptersArray = secondTableArrayTwo.SecondTitle
}
}
import UIKit
class Subchapters: UITableViewController {
var SubChaptersArray = [String]()
var identities = [String]()
var data = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
identities = ["G1","G2","G3","G4"]
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return SubChaptersArray.count
}
override func tableView(tableview: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCellWithIdentifier("SecondCell") as UITableViewCell!
cell.textLabel?.text = SubChaptersArray[indexPath.row]
return cell
}
// ignore
// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// let destViewController = segue.destinationViewController as! DrugNotes
// destViewController.FirstString = "drug data: need to seperate out to seperate pages" }
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let vcName = identities[indexPath.row]
let viewcontroller = storyboard?.instantiateViewControllerWithIdentifier(vcName)
self.navigationController?.pushViewController(viewcontroller!, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Passing coredata from tableview to another tableview

I am struggling with getting my care data to populate my second tableview controller. The data is populating the first tableview and I can select a row and the segue is used to go to the second table but the labels are not populated.
I've looked all over and have found older samples or obj-c but I cannot figure it out, so any help pointing this n00b in the right direction will be helpful.
Here is what I have, I think I am missing how to populate a variable to pass in prepareForSegue in the list tableview, but I could be wrong. I get a warning error in that function (Warning cannot assign value of type 'ListEntity' to type '[ListEntity]').
CoreData
Entity = ListEntity
Attributes = title, event & location (all as Strings)
listTableViewController
import UIKit
import CoreData
class ListTableViewController: UITableViewController {
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var lists = [ListEntity]()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "The List"
let addButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: #selector(ListTableViewController.addButtonMethod))
navigationItem.rightBarButtonItem = addButton
}
func addButtonMethod() {
print("Perform action")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
reloadData()
tableView.reloadData()
}
func reloadData() {
let fetchRequest = NSFetchRequest(entityName: "ListEntity")
do {
if let results = try managedObjectContext.executeFetchRequest(fetchRequest) as? [ListEntity] {
lists = results
}
} catch {
fatalError("There was an error fetching the list!")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lists.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ListCell") as! ListTableViewCell
let list = lists[indexPath.row]
cell.configurationWithSetup(list)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("DetailsSegue", sender: self)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "DetailsSegue" {
let destinationVC = segue.destinationViewController as! DetailsTableViewController
let indexPath : NSIndexPath = self.tableView.indexPathForSelectedRow!
print(indexPath.row) // Print the Row selected to console
// Place the code to pass data here?
// destinationVC.lists = lists[indexPath.row]
// Warning cannot assign value of type 'ListEntity' to type '[ListEntity]'
}
}
}
listTableViewCell
import UIKit
class ListTableViewCell: UITableViewCell {
#IBOutlet weak var titleLabel: UILabel!
func configurationWithSetup(list: AnyObject) {
titleLabel.text = list.valueForKey("title") as! String?
}
}
detailsTableViewController
import UIKit
import CoreData
class DetailsTableViewController: UITableViewController {
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var lists = [ListEntity]()
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("DataCell") as! DetailsTableViewCell
let list = lists[indexPath.row]
cell.configurationWithSetup(list)
return cell
}
}
detailsTableViewCell
import UIKit
import CoreData
class DetailsTableViewCell: UITableViewCell {
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var eventLabel: UILabel!
#IBOutlet weak var locationLabel: UILabel!
func configurationWithSetup(list: AnyObject) {
titleLabel.text = list.valueForKey("title") as! String?
eventLabel.text = list.valueForKey("event") as! String?
locationLabel.text = list.valueForKey("location") as! String?
}
}
The warning contains the answer - just change
var lists = [ListEntity]() to
var lists = ListEntity(), or var lists:ListEntity! and when you prepare for segue set that value.
Then you will need to change
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("DataCell") as! DetailsTableViewCell
// as data source is not array you can just you the item you passed
// let list = lists[indexPath.row]
cell.configurationWithSetup(lists)
return cell
}
You should use a static table view if you just want one cell
More info per you current issue
class DetailsTableViewController: UITableViewController {
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var theDetailListEntity:ListEntity!
override func viewDidLoad() {
super.viewDidLoad()
print(theDetailListEntity) // check that you passed it across
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("DataCell") as! DetailsTableViewCell
cell.configurationWithSetup(theDetailListEntity)
return cell
}
}
Don't forget to add prepare for segue in the listTableViewController otherwise theDetailListEntity won't be set... and then it will crash.
Depending on how you set up your segue, it may differ. But this is what you need
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("showMyDetailView", sender: indexPath)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showMyDetailView" {
guard let
vc = segue.destinationViewController as? DetailsTableViewController,
ip = sender as? NSIndexPath else { fatalError() }
let item = lists[ip.row]
vc.theDetailListEntity = item
// set the item in the next VC
tableView.deselectRowAtIndexPath(ip, animated: true)
}
}

fatal error two table view in UIview

in my app i want to display two table view in an UIViewController but i've a fatal error : fatal error: unexpectedly found nil while unwrapping an Optional value
can someone help me about this?
here is the full code of the uiview
class MyPropertiesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//table view extended
#IBOutlet weak var extandedTableViex: UITableView!
// table view standart
#IBOutlet weak var standartTableView: UITableView!
//list of data
let stdlist = ["1","2","3", "4","5","6","7","8","9"]
let Extlist = ["E1","E2" ]
//cell indentifier
let stdcellIdentifier = "stdcell"
let extcellIdentifier = "extcell"
override func viewDidLoad() {
super.viewDidLoad()
standartTableView.delegate = self
standartTableView.dataSource = self
standartTableView.delegate = self
standartTableView.dataSource = self
standartTableView.scrollEnabled = false
extandedTableViex.scrollEnabled = false
self.standartTableView.registerClass(GuaranteeCell.self, forCellReuseIdentifier: stdcellIdentifier)
self.extandedTableViex.registerClass(GuaranteeCell.self, forCellReuseIdentifier: extcellIdentifier)
}
//count cell
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == standartTableView {
return self.stdlist.count;
} else {
return self.Extlist.count;
}
}
// add cell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if tableView == standartTableView {
let cell:GuaranteeCell = self.standartTableView.dequeueReusableCellWithIdentifier(stdcellIdentifier) as! GuaranteeCell
print("list-element " + self.stdlist[indexPath.row])
print(indexPath.row)
cell.guaranteeLabel.text = self.stdlist[indexPath.row]
return cell
} else {
let cell2:GuaranteeCell = self.extandedTableViex.dequeueReusableCellWithIdentifier(extcellIdentifier) as! GuaranteeCell
cell2.guaranteeLabel.text = String(self.Extlist[indexPath.row])
return cell2
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { }
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
thanks
Check if your cell class is really GuaranteeCell (probably the error is there)

Swift: Passing data from a tableView in a ViewController to another ViewController

I'm trying to pass the indexPath.row data from the selected cell to the next view controller using both the didSelectCellAtIndexPath and the prepareForSegue methods but the value isnt passing through.
Code for both ViewControllers is show below:
import UIKit
class MainMenu: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource {
// array of the menu options
let mainMenuOptions = ["Exercises 1", "Exercises 2", "Exercises 3"]
// UITableView
#IBOutlet weak var exerciseOptions: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
exerciseOptions.delegate = self
exerciseOptions.dataSource = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Table configuration
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "ExercisesTableViewCells"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ExercisesTableViewCell
cell.textLabel!.text = mainMenuOptions[indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
// Segue to VC based on row selected
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 0{
self.performSegueWithIdentifier("SegueToExercises", sender: self)
}
else if indexPath.row == 1{
self.performSegueWithIdentifier("SegueToExercises", sender: self)
}
else{
self.performSegueWithIdentifier("SegueToReminders", sender: self)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "SegueToExercise"){
let viewController = segue.destinationViewController as? ExerciseMenu
viewController!.mainMenuValue = exerciseOptions.indexPathForSelectedRow!.row
}
}
For the Second View Controller:
import UIKit
class ExerciseMenu: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var exerciseOptionsTitle: UILabel!
#IBOutlet weak var exerciseOptionsTable: UITableView!
#IBAction func beginWorkout(sender: AnyObject) {
}
// receives data from MainMenu
var mainMenuValue: Int!
override func viewDidLoad() {
super.viewDidLoad()
exerciseOptionsTable.delegate = self
exerciseOptionsTable.dataSource = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "ExerciseMenuCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ExercisesTableViewCell
cell.textLabel!.text = String(mainMenuValue)
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
See this thread for possible explanations for this behavior.
The first step of troubleshooting would be to put a breakpoint in your prepareForSegue method to see if exerciseOptions.indexPathForSelectedRow is already nil at that point, in which case something is happening before the segue even occurs that's messing with the value (which the link above can help you diagnose).
Try making a property in your table view controller called something like selectedRow, and in didSelectRowAtIndexPath, set self.selectedRow = indexPath.row. This way you have your own variable that'll be more reliable than exerciseOptions.indexPathForSelectedRow. Then change the code in prepareForSegue appropriately. So to give you the full methods as I'm envisioning them:
(As a property of the first view controller) var selectedRow: Int?
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 0{
self.performSegueWithIdentifier("SegueToExercises", sender: self)
self.selectedRow = 0
}
else if indexPath.row == 1{
self.performSegueWithIdentifier("SegueToExercises", sender: self)
self.selectedRow = 1
}
else{
self.performSegueWithIdentifier("SegueToReminders", sender: self)
self.selectedRow = indexPath.row
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "SegueToExercise"){
let viewController = segue.destinationViewController as? ExerciseMenu
viewController!.mainMenuValue = self.selectedRow!
}
}
Disclaimer: I'm still learning Swift, so my judgment regarding optionals/optional unwrapping might be unideal for a technical reason I'm not aware of, but the overall theory here is sound, I think.

Does not conform to UITableViewDataSource - Parse app

I'm using a UITableView in a ViewController connected to TodayViewController. I want to use data from my Parse database to load into the TableView.
Here is my TodayViewController class:
import UIKit
class TodayViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var InfoTableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
InfoTableView!.delegate = self
InfoTableView!.dataSource = self
loadParseData()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadParseData() {
let query : PFQuery = PFQuery(className: "News")
query.orderByDescending("Headline")
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("NewCell") as! PFTableViewCell!
if cell == nil {
cell = PFTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "NewCell")
}
//Extract values from the PFObject to display in the table cell
if let Headline = object?["Headline"] as? String {
cell?.textLabel?.text = Headline
}
if let Subtitle = object?["SubtitleText"] as? String {
cell?.detailTextLabel?.text = Subtitle
}
return cell
}
This error crops up:
How do I solve the problem? Is there any mistake in the overall structure? Do request for more information if required.
Yes you are not confirm to protocol UITableViewDataSource because you don't have a required method
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
So you need to inherit PFQueryTableViewController to use the methods you want
class TodayViewController: PFQueryTableViewController {
...
}
I think you have implemented all the delegate methods of tableview outside the main class, i mean there will be a open parenthesis { and the close parenthesis should be end of all the methods. try like this
import UIKit
class TodayViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var InfoTableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
InfoTableView!.delegate = self
InfoTableView!.dataSource = self
loadParseData()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadParseData() {
let query : PFQuery = PFQuery(className: "News")
query.orderByDescending("Headline")
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("NewCell") as! PFTableViewCell!
if cell == nil {
cell = PFTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "NewCell")
}
//Extract values from the PFObject to display in the table cell
if let Headline = object?["Headline"] as? String {
cell?.textLabel?.text = Headline
}
if let Subtitle = object?["SubtitleText"] as? String {
cell?.detailTextLabel?.text = Subtitle
}
return cell
}
}
Hope this will help.

Resources