class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
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)!
var artists: AnyObject = dict.objectForKey("Artist")!
var stages: AnyObject = dict.objectForKey("Stage")!
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
}
return cell!
}
}
Hey all,
I'm new to swift so just experimenting with some things. What I'm trying to do is filling my table with content from a plist file. I know this isn't the best way! I already loaded the list successfully. My println(artists) returns what I want as well does the stages. The only problem is if I call artists or stages outside my viewDidLoad function it doesn't work. Why is that and how do I solve it?
Thanks in advance.
Greets,
Wouter
The variables "artists" and "stages" do not exists outside of the viewDidLoad-Function scope. You have to define them as properties to access them outside of the viewDidLoad-function. Like this
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var artists: AnyObject?
var stages: AnyObject?
override func viewDidLoad() {
...
artists: AnyObject = dict.objectForKey("Artist")
...
}
Related
I am creating an app that is retrieving data from Firebase. In my 'MealViewController' I have a TableView that has the view controller as it's delegate and data source. I am getting the issue "Type 'MealViewController" does not conform to protocol 'UITableViewDataSource' because it requires both :numberOfRowsInSection: and :cellForRowAtIndexPath: . However, when I add both, another issue appears - 'Definition conflict with previous value'. I've looked through all the Stack Overflow issues related to this, and no luck has been had. Here's my View Controller:
class MealViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var bgImage: UIImageView?
var image : UIImage = UIImage(named: "pizza")!
#IBOutlet weak var blurEffect: UIVisualEffectView!
#IBOutlet weak var mealTableView: UITableView!
var items = [MealItem]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
bgImage = UIImageView(image: image)
bgImage?.contentMode = .ScaleAspectFill
bgImage!.frame = view.layer.bounds
self.view.addSubview(bgImage!)
//self.bgImage?.addSubview(blurEffect)
//bgImage!.bringSubviewToFront(blurEffect)
view.bringSubviewToFront(blurEffect)
mealTableView.layer.cornerRadius = 5.0
mealTableView.layer.borderColor = UIColor.whiteColor().CGColor
mealTableView.layer.borderWidth = 0.5
let ref = Firebase(url: "https://order-template.firebaseio.com/grocery-items")
mealTableView.delegate = self
mealTableView.dataSource = self
// MARK: UIViewController Lifecycle
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(items.count)
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> MealsCellTableViewCell { //issue occurs here
let groceryItem = items[indexPath.row]
if let cell = mealTableView.dequeueReusableCellWithIdentifier("ItemCell") as? MealsCellTableViewCell {
cell.configureCell(groceryItem)
// Determine whether the cell is checked
self.mealTableView.reloadData()
return cell
}
}
func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// [1] Call the queryOrderedByChild function to return a reference that queries by the "completed" property
ref.observeEventType(.Value, withBlock: { snapshot in
var newItems = [MealItem]()
for item in snapshot.children {
let mealItem = MealItem(snapshot: item as! FDataSnapshot)
newItems.append(mealItem)
}
self.items = newItems
self.mealTableView.reloadData()
})
}
func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
}
func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
}
}
override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
bgImage = UIImageView(image: image)
bgImage?.contentMode = .ScaleAspectFill
bgImage!.frame = view.layer.bounds
self.view.addSubview(bgImage!)
view.bringSubviewToFront(blurEffect)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UITableView Delegate methods
}
The cellForRowAtIndexPath should look like this:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "ItemCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! MealsCellTableViewCell
let groceryItem = self.items[indexPath.row]
cell.configureCell(groceryItem)
return cell
}
Note that the returned cell is a MealsCellTableViewCell which is a subclass of UITableViewCell so it conforms to that class.
Don't change the function definition as that will make it not conform to what the delegate protocol specifies.
Here's a link to the Apple documentation for the specific implementation of custom tableView cells for reference.
Create a Table View
The problem is that your view controller's conformance to UITableViewDatasource cellForRowAtIndexPath method is not right. You should refactor your implementation of cellForRowAtIndexPath method like so:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let groceryItem = items[indexPath.row]
guard let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell") as? MealsCellTableViewCell else {
fatalError("No cell with identifier: ItemCell")
}
cell.configureCell(groceryItem)
return cell
}
You also need to move the datasource methods out of viewDidLoad method.
You return MealsCellTableViewCell instead of UITableViewCell in cellForRowAtIndexPath method, that's the reason.
i have a problem with appending an array, you can see my code, i checked the problem's line by: self.items.append(....)
the array is not appended and stay empty.
here is my code:
//
// ViewController.swift
// firer
//
// Created by mike matta on 06/01/2016.
// Copyright © 2016 Mikha Matta. All rights reserved.
//
import UIKit
import Firebase
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var showdatA: UILabel!
#IBOutlet weak var tableView: UITableView!
var items:[String] = []
var userFNAME:String = ""
var userDOB:String = ""
let textCellIdentifier = "TextCell"
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
// Do any additional setup after loading the view, typically from a nib.
///////////
let UsersChannel = Firebase(url: "https://MYFIREBASE.firebaseio.com/users")
UsersChannel.observeEventType(.ChildAdded, withBlock: { snapshot in
if let az = String?((snapshot.value.objectForKey("full_name"))! as! String) {
self.userFNAME = az
}
if let az2 = String?((snapshot.value.objectForKey("dob"))! as! String) {
self.userDOB = az2
}
print("\(self.userFNAME) - \(self.userDOB)")
self.items.append(self.userFNAME) // heeereeee what i am trying to doooooooo
})
// print(self.items)
}
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 items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as UITableViewCell
let row = indexPath.row
cell.textLabel?.text = items[row]
return cell
}
// MARK: UITableViewDelegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = indexPath.row
print(items[row])
}
}
i tryed to put the array definition inside the viewdidload() it works...but i need it outside it (like my code)..
i tryed to put the array outside the async block too...still not appending....any one ?
I think that your code works !
The question is :
Why do you think that your array is still empty ?
You have to think the order that your instructions are executed.
At this line :
// print(self.items);
Your array is still empty because the closure is not yet called.
Put this line just after the append and you will see.
And, Just add self.tableView.reloadData() after your append and you will be happy :)
(It will say to your tableview to recall the delegate methods (numberOfRowsInSection ...) )
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.
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.
I'm trying to make a view controller that has one text field that populates the tableview below, ideally the user will be able to continue to add to the tableview without jumping between two views.
I previously had it working with the text field on one view that populates a UITableView and used prepareForSegue to push the data to the table, but I haven't been able to get it to work with just one view.
Can anyone please point out where I'm going wrong or push me to a tutorial / documentation to help?
Edit: Clarity
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
#IBOutlet var tableView: UITableView!
#IBOutlet weak var textField: UITextField!
var items: [String] = ["Pls", "work", "pls", "work", "pls"]
var foodGroup: FoodGroup = FoodGroup(itemName:"")
//var foodGroup: [FoodGroup] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel.text = self.items[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("Selected cell #\(indexPath)")
}
func addFood(sender: AnyObject!) {
if (countElements(self.textField.text) > 0) {
self.foodGroup = FoodGroup(itemName: self.textField.text)
}
}
#IBAction func addFoodToList() {
let source = FoodGroup
let foodGroup:FoodGroup = source.foodGroup
if foodGroup.itemName != "" {
self.foodGroup.append(foodGroup)
self.tableView.reloadData()
}
}
}
It seems like your intention here is to have your dataSource be an array of FoodGroup objects. If this is indeed the case you can get rid of your foodGroup instance variable and update your items definition to be like so:
var items = [FoodGroup]()
then in addFoodToList:
if self.textField.text != "" {
let foodGroup = FoodGroup(itemName: self.textField.text)
self.items.append(foodGroup)
self.tableView.reloadData()
}
and finally in cellForRowAtIndexPath:
var cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
let foodGroup = self.items[indexPath.row] as FoodGroup
cell.textLabel.text = foodGroup.itemName
return cell
Also I don't quite see the intention of your the addFood(sender: AnyObject!) function. Looks like cruft. I would get rid of it. Good luck!