Populate a UITableView with plist - uitableview

i'm trying to get a plist to populate uitableview
The plist looks like this :
the code i'm having trouble with :
class GravidMenu: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet
var tableView: UITableView
var dict = NSMutableArray(contentsOfFile: NSBundle.mainBundle().pathForResource("links", ofType: "plist"))
var txt : NSString = dict.valueForKey("menuPunkt") as NSString //this throws a error : GravidMenu.Type does not have a member named dict
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return self.dict.count;
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
if let row = indexPath?.row {
cell.textLabel.text = self.txt[row] // throws a error Nsstring does not have a a member named subscript
println("Text \(txt)")
}
return cell
}
Seems like i'm getting closer.
UPDATE
Showing Full code
with adjustments to cell.label and to var txt. also moved it some code to viewDidLoad which breaks it all it seems
import UIKit
import Foundation
class GravidMenu: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet
var tableView: UITableView
override func viewDidLoad() {
super.viewDidLoad()
var dict = NSMutableArray(contentsOfFile: NSBundle.mainBundle().pathForResource("links", ofType: "plist"))
var txt : NSArray = dict.valueForKey("menuPunkt") as NSArray
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return self.dict.count; // Throws Error GravidMenu does not have a member named dict
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
if let row = indexPath?.row {
cell.textLabel.text = "\(txt.objectAtIndex(indexPath.row))"
println("Text \(txt)")
}
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
println("You selected cell #\(indexPath.row)!")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
UPDATE
let dict : NSMutableArray! = NSMutableArray(contentsOfFile: NSBundle.mainBundle().pathForResource("links", ofType: "plist"))
var txt : NSArray! = dict?.valueForKey("menuPunkt") as? NSArray!
this is causing me trouble. it keeps saying that "GravidMenu has no member named dict" in the var txt line... anyone ? help

all this code paste in viewDidLoad:
var dict : NSMutableArray = NSMutableArray(contentsOfFile: NSBundle.mainBundle().pathForResource("links", ofType: "plist"))
var txt : NSString = dict!.valueForKey("menuPunkt") as NSString
I'll search you the reason why you need to write in the viewDidLoad.
I recommend you put a question mark because you can not know if it will be nil, (if not find the file)
and also for dict!.
hope i helped :)
UPDATE:
let dict : NSMutableArray! = NSMutableArray(contentsOfFile: NSBundle.mainBundle().pathForResource("links", ofType: "plist"))
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var txt : NSString = dict!.valueForKey("menuPunket") as NSString;
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return self.dict!.count;
}
its work for me now.

Related

Gets number of rows but doesn't print

I have a program written in Swift 3, that grabs JSON from a REST api and appends it to a table view.
Right now, I'm having troubles with getting it to print in my Tableview, but it does however understand my count function.
So, I guess my data is here, but it just doesn't return them correctly:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, HomeModelProtocal {
#IBOutlet weak var listTableView: UITableView!
func itemsDownloaded(items: NSArray) {
feedItems = items
self.listTableView.reloadData()
}
var feedItems: NSArray = NSArray()
var selectedLocation : Parsexml = Parsexml()
override func viewDidLoad() {
super.viewDidLoad()
self.listTableView.delegate = self
self.listTableView.dataSource = self
let homeModel = HomeModel()
homeModel.delegate = self
homeModel.downloadItems()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier: String = "BasicCell"
let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
let item: Parsexml = feedItems[indexPath.row] as! Parsexml
myCell.textLabel!.text = item.title
return myCell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return feedItems.count
}
override func viewDidAppear(_ animated: Bool) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Are you by any chance able to see the error that I can't see?
Note. I have not added any textlabel to the tablerow, but I guess that there shouldn't be added one, when its custom?
Try this code:
override func viewDidLoad() {
super.viewDidLoad()
print(yourArrayName.count) // in your case it should be like this print(feedItems.count)
}

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.

Read & Save setting an array in array in swift

I try to load this array out from my save setting "Mybookmarks", and try to write it in a table. That is in the setting =>
[["name" : "apple", "url": "http://www.apple.de"],
["name" : "youtube", "url": "http://www.youtube.de"]]
But it doesn't work, it said always crash. I want to load this kind of array and write it in a tableview.
Any idea on how to fix this so that it can read this from my "var defaults = NSUserDefaults.standardUserDefaults()".
// ViewController.swift
import UIKit
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {
// create references to the items on the storyboard
// so that we can animate their properties
var tableView: UITableView = UITableView()
var objects = []
override func viewDidLoad() {
super.viewDidLoad()
var defaults = NSUserDefaults.standardUserDefaults()
//read
if let testArray : AnyObject? = defaults.objectForKey("Mybookmarks") {
var objects : [NSString] = testArray! as! [NSString]
println("\(testArray)")
}
tableView.frame = CGRectMake(0, 0, 300, view.frame.height);
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(tableView)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.objects.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
let object = self.objects[indexPath.row]
cell.textLabel?.text = object["name"]!
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("You selected cell #\(indexPath.row)!")
}
}
the type of the array is an array of dictionaries [[String:String]] rather than array of strings [String]
var objects = [[String:String]]()
...
if let testArray : AnyObject? = defaults.objectForKey("Mybookmarks") {
objects = testArray as! [[String:String]]
}
Edit:
and connect the tableview instance in Interface Builder with an IBOutlet.
The instance you're creating with var tableView: UITableView = UITableView() is a brand new instance, it's different from those in IB
nevermind I see that this is not in [String:String]. This must be in let object:
[String:String] = self.objects[indexPath.row]
and now it works

Value's from plist to tableView

I'm trying to use a plist to fill my tableView. I've currently written this code. I'm not having any errors and I can run the app fine. The problem is the tableview remains empty. My println returns all the value's from my plist tho. If I request them outside my viewDidLoad function nothing comes up tho. Any idea what I'm doing wrong? Sorry for asking an almost similar question as my previous one. It's just that I'm trying to teach myself a new language.
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var artists: Array<String> = []
var stages: Array<String> = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let path = NSBundle.mainBundle().pathForResource("TableRowInfo", ofType: "plist")!
let dict = NSDictionary(contentsOfFile:path)!
artists = dict["Artist"] as Array<String>
stages = dict["Stage"] as Array<String>
println(artists)
println(stages)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return artists.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("InfoCell", forIndexPath: indexPath) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "InfoCell")
cell!.accessoryType = .DisclosureIndicator
}
cell?.textLabel?.text = artists[indexPath.row]
cell?.detailTextLabel?.text = stages[indexPath.row]
return cell!
}
}
Thanks in advance.

Table View doesn't show data from JSON

My Code:
import UIKit
class HomeVCHome: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var usernameLabel: UILabel!
#IBOutlet weak var tableView: UITableView!
var names: [String] = []
var contacts: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self;
self.tableView.dataSource = self;
let url=NSURL(string:"http://mysite/json.aspx")!
let allContactsData=NSData(contentsOfURL:url)
var allContacts: AnyObject! = NSJSONSerialization.JSONObjectWithData(allContactsData!, options: NSJSONReadingOptions(0), error: nil)
if let json = allContacts as? Array<AnyObject> {
print(json)
for index in 0...json.count-1 {
let contact : AnyObject? = json[index]
print(contact)
let collection = contact! as Dictionary<String, AnyObject>
print(collection)
print(collection["name"])
let name : AnyObject? = collection["name"]
let cont : AnyObject? = collection["cont"]
names.append(name as String)
contacts.append(cont as String)
}
}
println(names)
println(contacts)
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return self.names.count;
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
println("You selected name : "+names[indexPath.row])
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as? UITableViewCell
println("ok 1")
if !(cell != nil) {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "cell")
}
println("ok 2")
cell?.textLabel.text=self.names[indexPath.row]
cell?.detailTextLabel?.text = self.contacts[indexPath.row]
println("ok 3")
return cell!
}
}
i try to run, and i can't see my data in tableView... just blank in table View
and i try another code but the same result (table view blank)...
what should i do? i don't know its my mistake code or my simulator have problems like that...
pls change the method and try:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) as UITableViewCell
cell.textLabel.text=self.names[indexPath.row]
cell.detailTextLabel?.text = self.contacts[indexPath.row]
return cell
}

Resources