Swift: How to pass array items in tableview - ios

I'm trying to pass array values to a tableview.
# //4 println(items) it prints an array with values to my console. I want to have those results passed in to the tableview. The tableview is working but gets it's value from var list: [String] = ...
How do I get the println(items) in the var list: [String] = ... ?
Thanks!!
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var list: [String] = ["Row One", "Row Two", "Row Three" , "Row Four", "Row Five"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
var results = "today"
var subItem = "movie"
// hier moet de opegslagen bioscoop komen die door de gebruiker is opgeslagen als keuze
var cinemaFilter = "Pathé Arena"
// Get the Cinema's from scraper and SwiftyJSON
DataManager.getCinemaDataFromScraperWithSuccess { (ScraperData) -> Void in
let json = JSON(data: ScraperData)
if let itemName = json["results"][results][0][subItem]["text"].stringValue {
println("Film resultaten:")
}
//1
if let itemArray = json["results"][results].arrayValue {
//2
var items = [itemModel]()
//3
for itemDict in itemArray {
var itemName: String? = itemDict[subItem]["text"].stringValue
var itemTime: String? = itemDict["time"]["text"].stringValue
var itemCinema: String? = itemDict["cinema"]["text"].stringValue
if itemCinema == cinemaFilter {
var item = itemModel(name: itemName, time: itemTime, cinema: itemCinema )
items.append(item)
} else {
//println("is niet de ingestelde bioscoop")
}
}
//4
println(items)
}
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.list.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel?.text = self.list[indexPath.row]
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
println("You selected cell #\(indexPath.row)!")
}
}

Make items an instance variable of your view controller instead of a local variable, use it in the data source methods, and get rid of list.
You then need to decide what part of an item you want to show in cell.textLabel?.text, name, time, cinema, or some combination.

Instead of var items = [itemModel]() inside the func place it on class lavel so it's an instance. Then change
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count;
}
and the cell method accordingly to use items.

Related

How to reload TableVIew Using Model NSObject Class with MVVM

I want to reload TableView without tableview.reloadData() method for that i have used MVVM structure so i have attach model class to storyboard and the issue is that my tableview is reload first and then i get all data how should i solved this issue please help me if any one have a solution !!
This is storyboard model attach
Model Code :-
class MovieModel: Decodable{
var artistName: String = ""
var trackName: String = ""
init(artistName: String, trackName: String){
self.artistName = artistName
self.trackName = trackName
}
}
class ResultModel: Decodable{
var results = [MovieModel]()
init(results: [MovieModel]) {
self.results = results
}
}
My ViewModel File code :-
class MovieViewModel: NSObject {
var artistName: String = ""
var trackName: String = ""
var movieModel: MovieModel?
var movieData = [MovieViewModel]()
override init() {
}
init(movie: MovieModel) {
self.artistName = movie.artistName
self.trackName = movie.trackName
}
func getData(){
Service.shareInstance.getAllMovieData { (movie, error) in
if error == nil{
self.movieData = movie?.map({return MovieViewModel(movie: $0)}) ?? []
print(self.movieData)
}else{
print("\(String(describing: error))")
}
}
}
func numberOfRow(section:Int) -> Int{
return movieData.count
}
func cellForRow(indexPath: IndexPath) -> MovieViewModel{
return self.movieData[indexPath.row]
}
}
My ViewController Code :-
class ViewController: UIViewController {
#IBOutlet var movieVM: MovieViewModel?
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.movieVM?.getData()
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movieVM?.numberOfRow(section: section) ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
let movie = movieVM?.cellForRow(indexPath: indexPath)
cell?.textLabel?.text = movie?.artistName
cell?.detailTextLabel?.text = movie?.trackName
return cell!
}
}
In my case i am not reload tableview all this is done using ModelClass ! Thank You !!

How to have each UITableViewOption have its own data

I am trying to have each choice in my UITableView to have its own unique set of data. For example, in my table view I have a list of states, then when I click on a state, I want each state to have a list of cities that correspond specifically to it. I have attached my code below, the code is strictly for the UITableView only.
I'm new to Xcode/Swift.
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
let textCellIdentifier = "TextCell"
var states = ["Illinois", "Indiana", "Kentucky", "Michigan", "Ohio", "Pennsylvania", "Wisconsin"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return states.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier, for: indexPath)
let row = indexPath.row
cell.textLabel?.text = states[row]
return cell
}
private func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
let row = indexPath.row
print(states[row])
}
You can construct array model like this
struct MainItem {
var name:String
var cities:[String]
init(name:String,cities:[String]) {
self.name = name
self.cities = cities
}
}
//
let item1 = MainItem(name:"Illinois",cities:["city1","city2"])
let item2 = MainItem(name:"Indiana",cities:["city3","city4"])
var states = [item1,item2]
//
in cellForRowAt
cell.textLabel?.text = states[row].name
//
in didSelectRowAtIndexPath
let cities = states[row].cities
I recently did this by creating separate classes for each of the delegates I wanted to have. Move all of the table functions into a new class and create an instance of the class in your new controller. In the view did load function set the delegate for the first table. Whenever you switch tables with a button or whatever, do nextTable.delegate = xxxx.
View controller code:
let eventLogTableController = EventLogTableController()
let missedEventLogController = MissedEventTableController()
#IBOutlet weak var emptyTableLabel: UILabel!
#IBOutlet weak var missedEventLog: UITableView!
override func viewDidLoad() {
self.eventLog.delegate = eventLogTableController

How to add a cell to my Table View dynamically using a button

I am trying to add a cell to my table view with a button. Everything I have read and watched suggests that what I have written should work, but it doesn't. Any suggestions?
import UIKit
class RootViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {
private var cellPointSize: CGFloat!
private var albumsList: AlbumList!
private var albums:[Album]!
private let albumCell = "Album"
#IBOutlet var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let preferredTableViewFont = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
cellPointSize = preferredTableViewFont.pointSize
albumsList = AlbumList.sharedAlbumList
albums = albumsList.albums
self.myTableView.dataSource = self
self.myTableView.delegate = self
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return albums.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Albums"
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = myTableView.dequeueReusableCellWithIdentifier(albumCell, forIndexPath: indexPath) as! UITableViewCell
//cell.textLabel?.font = fontForDisplay(atIndexPath: indexPath)
cell.textLabel?.text = albums[indexPath.row].name
cell.detailTextLabel?.text = albums[indexPath.row].artist
return cell
}
#IBAction func addNewAlbumAction(sender: UIBarButtonItem) {
var newAlbum = Album(nameIn: "New Title", yearIn: "New Year", artistIn: "New Artist", labelIn: "New Label")
albumsList.addAlbum(newAlbum)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.myTableView.reloadData()
})
}
func saveData(albumObject: Album) {
var archiveArray = NSMutableArray(capacity: albums.count)
for a in albums {
var albumEncodedObject = NSKeyedArchiver.archivedDataWithRootObject(a)
archiveArray.addObject(albumEncodedObject)
}
var userData = NSUserDefaults()
userData.setObject(archiveArray, forKey: "albums")
userData.synchronize()
}
My albums array is adding the data correctly. I can see the albums in the debugger. The delegate methods are never being called after the first time when the app loads. Any ideas?
in tableView:numberOfRowsInSection:, it returns albums.count
but when the button is pressed, you add the new album to albumsList
The problem is, albums will not get update.
So I think you should return albumsList.albums.count instead.
and in tableView:cellForRowAtIndexPath:, you modify the cell correspond to albumsList.albums[indexPath.row]

UITableView going out of view

i have a UITableView with multiple selection enabled with checkmarks. When i make selection that are all visible in the view, i don't run into any errors. However, if i scroll down further and place a selected item out of view, i get errors and even though the row stays selected, the checkmark goes away.
import Foundation
import Parse
import UIKit
class customerMenuVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var menuTV: UITableView!
var menuItems: [String] = ["Hello"]
var menuPrices: [Double] = [0.0]
var orderSelection: [String] = []
var priceSelection: [Double] = []
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return menuItems.count
}
func tableView(tableView: UITableView, numberOfColumnsInSection section: Int) -> Int
{
return 1;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "mycell")
cell.textLabel!.text = "\(menuItems[indexPath.row])\t $\(menuPrices[indexPath.row])"
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
//tableView.deselectRowAtIndexPath(indexPath, animated: true)
let cell = tableView.cellForRowAtIndexPath(indexPath)
cell!.accessoryType = .Checkmark
orderSelection.append(cell!.textLabel!.text!)
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath)
{
let cell = tableView.cellForRowAtIndexPath(indexPath)
cell!.accessoryType = .None
}
override func viewDidLoad() {
super.viewDidLoad()
menuTV.allowsMultipleSelection = true
let resMenu = resUser.sharedInstance
var resName = resMenu.nameStr
var resID = resMenu.idStr
var menuQ = PFQuery(className: "menu")
menuQ.getObjectInBackgroundWithId(resID){
(menus: PFObject?, error: NSError?) -> Void in
if error == nil && menus != nil {
let items: [String] = menus?.objectForKey("menuItems") as! Array
let prices: [Double] = menus?.objectForKey("menuPrices") as! Array
self.menuItems = items
self.menuPrices = prices
self.menuTV.reloadData()
}
}
}
#IBAction func continueButton(sender: AnyObject) {
let selections = menuTV.indexPathsForSelectedRows() as! [NSIndexPath]
var indexCount = selections.count
println(indexCount)
var x = 0
while x < indexCount
{
println(x)
let currentCell = menuTV.cellForRowAtIndexPath(selections[x]) as? UITableViewCell?;
println(x)
println(selections[x].row.description)
orderSelection.append(currentCell!!.textLabel!.text!)
println(orderSelection[x])
x++
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
This is how table views work.
When a cells scrolls off-screen, it gets tossed into the recycle queue and then used again to display data for a different indexPath in your data.
Any time the user makes any changes to the data for a cell you should save it to your data model (usually an array of information, or maybe an array of arrays if you're using a sectioned table view.) Then you should tell the table view to redisplay the changed cell. The cellForRowAtIndexPath method picks up the changed data and shows the changes to the cell. If the cell scrolls off-screen and then scrolls back on-screen, it gets displayed with the correct settings.
This applies to keeping track of which cells are selected as well.

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