How can I pass the value from a view to another view in iOS? - ios

import UIKit
class TableController: UITableViewController {
var items = NSMutableArray()
var TableData:Array< String > = Array < String >()
var json:String = ""
var quantity2: Int = 0
var shortDate: String = ""
#IBOutlet var myTableView: UITableView!
var arrayOfMenu: [Nutrisi] = [Nutrisi]()
override func viewDidLoad() {
super.viewDidLoad()
self.setUpMenu()
self.myTableView.delegate = self
self.myTableView.dataSource = self
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayOfMenu.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CustomCell = tableView.dequeueReusableCellWithIdentifier("cell") as! CustomCell
let menu = arrayOfMenu[indexPath.row]
cell.setCell(menu.type, rightlabeltext: menu.unit, imagename: menu.image)
var data = Nutritiondata(type: menu.type, amount: String(cell.value).toInt()!)
var json = JSONSerializer.toJson(data)
self.json = json
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func do_table_refresh()
{
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
return
})
}
func setUpMenu()
{
var json: JSON = JSON (data: NSData())
let frame:CGRect = CGRect(x: 110, y: 300, width: view.frame.width, height: 700)
self.tableView.frame = frame
DataManager.getnutritionsDataFromFileWithSuccess{ (data) -> Void in
json = JSON(data: data)
let results = json["results"]
for (index: String, subJson: JSON) in results {
}
for (var i = 0; i < json["nutritions"].count; i++) {
if let type = json["nutritions"][i]["type"].string {
if let icon: AnyObject = json["nutritions"][i]["icon"].string {
self.items.addObject(icon)
if let unit = json["nutritions"][i]["unit"].string {
dispatch_async(dispatch_get_main_queue(), {self.tableView!.reloadData()})
var menu = Nutrisi(type: type, unit: unit, image: icon as! String)
self.arrayOfMenu.append(menu)
self.TableData.append(type + unit )
self.do_table_refresh();
}
}
}
}
}
}
}
I've this code, and works well on table controller view, but I want to make a new view controller that prints json (json on table controller works well, and printed out)
So, I made a new view controller connected to another class named senddata what command that I should use to print json on there, I want to print that json data when the button pressed:
import UIKit
class SendData: UIViewController{
#IBAction func tes(sender: AnyObject) {
println()
}
override func viewDidLoad() {
super.viewDidLoad()
}
}

You could put that JSON Data in a global struct, so it would end up looking like this.
TableViewController.swift
struct JSON {
static var JSONData = ""
}
class TableController: UITableViewController {
var items = NSMutableArray()
var TableData:Array< String > = Array < String >()
var json:String = ""
var quantity2: Int = 0
var shortDate: String = ""
#IBOutlet var myTableView: UITableView!
var arrayOfMenu: [Nutrisi] = [Nutrisi]()
override func viewDidLoad() {
super.viewDidLoad()
self.setUpMenu()
self.myTableView.delegate = self
self.myTableView.dataSource = self
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayOfMenu.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CustomCell = tableView.dequeueReusableCellWithIdentifier("cell") as! CustomCell
let menu = arrayOfMenu[indexPath.row]
cell.setCell(menu.type, rightlabeltext: menu.unit, imagename: menu.image)
var data = Nutritiondata(type: menu.type, amount: String(cell.value).toInt()!)
var json = JSONSerializer.toJson(data)
JSON.JSONData = json
return cell
}
SendData.swift
class SendData: UIViewController{
#IBAction func tes(sender: AnyObject) {
println(JSON.JSONData)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}

Related

Update initialized Data in array with variable then pass array to next view controller

I'm having issues moving the data from the selected cells from the (service2viewcontroller) to the (confirmorderviewcontroller). I am trying to move the cell data (cells with a stepper.value above 0(var quantity > 0.0 (in Service2ViewController))), I was told to pass the array to the next view controller, to do so for a stepper value above 0 I would need to also send the indexpath.row for the rows with a quantity variable above 0 correct? I don't know how to do this if anyone can help I would greatly appreciate it. also the label is not updating when I use the stepper it stays at 0, can I place the quantity variable inside of the array? the total price label in the view controller continues to function and the data is sent to the (confirmorderviewcontroller) with no issues.
first TableView (data is input and forwarded)
class Service2ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var service2Total: UILabel!
#IBOutlet weak var service2TableView: UITableView!
// service data
var Wash: [Service2] = []
//stepper and price calculation
var quantity = Double()
var totalPrice : Double = 0.0
var priceList = [Int : Double]()
var totalProductPrice = [Int : Double]()
var label : Int!
override func viewDidLoad() {
super.viewDidLoad()
Wash = Options2()
if Int(quantity) > 0{
service2TableView.reloadData()
}
priceList[0] = 3.51//price list
priceList[1] = 5.51
service2Total.text = "$0.00"
}
// create data array
func Options2() -> [Service2]{
var washOptions: [Service2] = []
let option1 = Service2(titled: "Test", pricing: "$3.51", image: #imageLiteral(resourceName: "Wash&Fold"), description:"Testing the description box", quantity: Int(quantity))
let option2 = Service2(titled: "Test", pricing: "$5.51", image: #imageLiteral(resourceName: "Wash&Fold"), description: "Testing the description box", quantity: Int(quantity))
washOptions.append(option1)
washOptions.append(option2)
return washOptions
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Wash.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let Wash1 = Wash[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "Service2Cell", for: indexPath) as! Service2TableViewCell
cell.setService(Wash: Wash1)
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 133
}
#IBAction func stepperAcn(_ sender: UIStepper) {
//change label value with stepper
let cellPosition = sender.convert(CGPoint.zero, to: service2TableView)
let indPath : IndexPath = service2TableView.indexPathForRow(at: cellPosition)!
quantity = sender.value
let getCurrentProductPrice : Double = priceList[indPath.row]! * sender.value
totalPrice = gettingPriceLabel(indPath: indPath, getCurrentProductPrice: getCurrentProductPrice)
if totalPrice == 0{
service2Total.text = ("$0.00")
}
else{
service2Total.text = ("$")+String(totalPrice)
}
print("total price",totalPrice)
print("quantity double",quantity)
service2TableView.reloadData()
}
func gettingPriceLabel(indPath: IndexPath, getCurrentProductPrice : Double) -> Double
{
totalProductPrice[indPath.row] = getCurrentProductPrice
var totalCost : Double = 0.0
let valuesArr = Array(totalProductPrice.values)
for i in 0..<valuesArr.count
{
totalCost = totalCost + valuesArr[i]
}
return totalCost
}
// add function to collect (didSelectRowAt) and send selected data to cart and prepare for segue
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
// change sender to
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let DestViewController: ConfirmorderViewController = segue.destination as! ConfirmorderViewController
if totalPrice > 0.00{
DestViewController.amount = totalPrice
}
}
}
service initializer
class Service2
{
var service2Title: String
var service2Image: UIImage
var Service2Pricing: String
var service2Description: String
var service2Quantity: Int
init(titled: String, pricing: String, image: UIImage, description: String, quantity: Int){
self.service2Title = titled
self.Service2Pricing = pricing
self.service2Image = image
self.service2Description = description
self.service2Quantity = quantity
}
}
Service 2 TableViewCell
class Service2TableViewCell: UITableViewCell {
#IBOutlet weak var service2Title: UILabel!
#IBOutlet weak var service2Stepper: UIStepper!
#IBOutlet weak var service2StepperLbl: UILabel!
#IBOutlet weak var service2Pricing: UILabel!
#IBOutlet weak var service2Image: UIImageView!
#IBOutlet weak var service2Description: UILabel!
func setService(Wash: Service2){
service2Image.image = Wash.service2Image
service2Pricing.text = Wash.Service2Pricing.description
service2Title.text = Wash.service2Title
service2Description.text = Wash.service2Description
service2StepperLbl.text = Wash.service2Quantity.description
}
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
}
}
Second TableView (receives data)
class ConfirmorderViewController: UIViewController{
#IBOutlet weak var Total: UILabel!
#IBOutlet weak var confirmOrderTableView: UITableView!
var titled = [String]()
var amount: String = ""
//var quantity = String()
var image1 = [UIImage]()
var Price = [Double]()
override func viewDidLoad() {
super.viewDidLoad()
Total.text = amount
confirmOrderTableView.reloadData()
}
}
extension ConfirmorderViewController: UITableViewDataSource, UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titled.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ConfirmOrderTableViewCell") as! ConfirmOrderTableViewCell
cell.coTitle?.text = titled[indexPath.row]
cell.coImg?.image = image1[indexPath.row]
//cell.coQuantity.text = quantity
cell.coPrice?.text = Price.description
return cell
}
}
I have tried here. I got list of row numbers having more than 0 order. I have it stored in whichRowToBeAdd. If user decreased to Zero, respective rows will removed from this array.
With the help of Singleton Class, we can store whatever we need to show in NextViewController
var whichRowToBeAdd = [Int]() // GLOBAL
#IBAction func stepperAcn(_ sender: UIStepper) {
//change label value with stepper
let cellPosition = sender.convert(CGPoint.zero, to: service2TableView)
let indPath : IndexPath = service2TableView.indexPathForRow(at: cellPosition)!
if Int(sender.value) == 0
{
if whichRowToBeAdd.contains(indPath.row)
{
whichRowToBeAdd.remove(at: whichRowToBeAdd.index(of: indPath.row)!)
}
else
{
}
}
else
{
if whichRowToBeAdd.contains(indPath.row)
{
}
else
{
whichRowToBeAdd.append(indPath.row)
}
}
//....
//..... Your Code in your answer
}
// After stepper Action, final click of Button, which moves to Next ViewController
#IBAction func goToConfirmOrder(_ sender: UIBarButtonItem) {
print("\n\n Val_ ", whichRowToBeAdd)
singleTon.sharedInstance.orderDict.removeAll()
for i in 0..<whichRowToBeAdd.count
{
let indPath = IndexPath(row: whichRowToBeAdd[i], section: 0)
let newCell = tblVw.cellForRow(at: indPath) as! Service2TableViewCell
print("qweqwe ",newCell.testLbl.text)
let name : String = newCell.service2Title.text!
let image : UIImage = newCell.service2Image.image
let quantity : Int = Int(newCell.service2StepperLbl.text!)!
getOrderOneByOne(productName: name, productImage: image, productQuantity: quantity)
if i == (whichRowToBeAdd.count - 1)
{
self.performSegue(withIdentifier: "confirmOrderVC", sender: nil)
}
}
}
func getOrderOneByOne(productName: String, productImage : UIImage, productQuantity: Int)
{
let createDict = ["productName" : productName, "productImage" : productImage, "productQuantity" : productQuantity] as [String : Any]
singleTon.sharedInstance.orderDict.append(createDict)
}
Singleton Class
class singleTon: NSObject {
static let sharedInstance = singleTon() // Singleton Instance
var orderDict = [[String : Any]]() // Dictionary Declaration
}
Next ViewController
class ConfirmOrderViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("\n\norderDict.coun ", singleTon.sharedInstance.orderDict)
}
}
With this, you can display datas in TableView in this ConfirmOrderViewController.

No data is showing up in my UITableView

My IBOutlet for songName is set up correctly, but for some reason
import UIKit
class QueueController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
let testUser = Profile.init(username: "test", followers: [], following: [])
let songOne = Song.init(name: "S1", UWR: testUser.username, genre: "rock", artist: "s1")
var moreSongs = [Song]()
moreSongs = [Song(name: "gah", UWR: testUser.username, genre: "gahh", artist: "GAH")]
Queue.createQueue("2321x", creator: testUser, firstSong: songOne, additionalSongs: moreSongs)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Queue.theQueue!.count
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if let feed = Queue.theQueue {
return feed.count
} else {
return 0
}
}
func songIndex(cellIndex: Int) -> Int {
return tableView.numberOfSections - cellIndex - 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let song = Queue.theQueue![songIndex(indexPath.section)]
let cell = tableView.dequeueReusableCellWithIdentifier("queueCell", forIndexPath: indexPath) as! QueueCell
//cell.textLabel?.text = song.name this doesnt work also
cell.songName.text = "asdad"
return cell
}
}
For my Queue class:
import UIKit
class Queue {
let creator:Profile!
let planetID:String!
let beginningSong: Song!
var feed:Array<Song>?
static var theQueue:Array<Song>?
init (id:String!, creator:Profile!, firstSong:Song!) {
self.planetID = id
self.creator = creator
self.beginningSong = firstSong
}
func addSong (song: Song) {
feed?.append(song)
}
static func createQueue (id:String!, creator:Profile!, firstSong:Song!, additionalSongs: [Song]) {
let temp = Queue(id: id, creator: creator, firstSong: firstSong)
for song in additionalSongs {
temp.addSong(song)
}
self.theQueue = temp.feed
}
}
Song class:
import UIKit
class Song {
let name:String!
let userWhoRequested:String!
let genre: String?
let artist: String?
init (name:String!, UWR:String!, genre:String?, artist:String?) {
self.name = name
self.userWhoRequested = UWR
self.genre = genre
self.artist = artist
}
}
class QueueCell: UITableViewCell {
#IBOutlet weak var songName:UILabel!
#IBOutlet weak var userPicture:UIImageView!
#IBOutlet weak var isCurrent:UIImageView!
}
The table view displays properly but no data shows up in my controller, and I'm not sure why. The reuse cell identifier is also correct. The data in viewDidLoad() is also in my app delegate's func application.
Thanks!
Your problem is with the feed inside your CreateQueue method, that was never initialized
And change
var feed:Array<Song>?
to
var feed = [Song]()

UISearchController number of rows not getting called

I'm trying to send a request to search for movies, but when i tap on the search bar to write the text i get a crash in cellforrow and it's not calling numberofrows neither the request. Here's my code so far:
class InTheaters: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate {
#IBOutlet weak var poster: UIImageView!
#IBOutlet weak var movieTitle: UILabel!
#IBOutlet weak var date: UILabel!
#IBOutlet weak var duration: UILabel!
#IBOutlet weak var rating: UILabel!
#IBOutlet var theatersTable: UITableView!
#IBOutlet weak var starsView: CosmosView!
var results = [Movie]()
var searchResults = [Search]()
var resultSearchController: UISearchController!
private let key = "qtqep7qydngcc7grk4r4hyd9"
override func viewDidLoad() {
super.viewDidLoad()
self.resultSearchController = UISearchController(searchResultsController: nil)
self.resultSearchController.searchResultsUpdater = self
self.resultSearchController.dimsBackgroundDuringPresentation = false
self.resultSearchController.searchBar.sizeToFit()
self.resultSearchController.searchBar.placeholder = "Search for movies"
self.theatersTable.tableHeaderView = self.resultSearchController.searchBar
self.theatersTable.reloadData()
getMovieInfo()
customIndicator()
infiniteScroll()
}
func customIndicator() {
self.theatersTable.infiniteScrollIndicatorView = CustomInfiniteIndicator(frame: CGRectMake(0, 0, 24, 24))
self.theatersTable.infiniteScrollIndicatorMargin = 40
}
func infiniteScroll() {
self.theatersTable.infiniteScrollIndicatorStyle = .White
self.theatersTable.addInfiniteScrollWithHandler { (scrollView) -> Void in
self.getMovieInfo()
}
}
func getMovieInfo() {
Alamofire.request(.GET, "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/in_theaters.json?page_limit=10&page=1&country=us&apikey=\(key)").responseJSON() {
(responseData) -> Void in
if let swiftyResponse = responseData.result.value {
let movies = Movies(JSONDecoder(swiftyResponse))
for movie in movies.allMovies {
self.results.append(movie)
}
}
self.theatersTable.reloadData()
self.theatersTable.finishInfiniteScroll()
}
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
self.searchResults.removeAll(keepCapacity: false)
if (searchController.searchBar.text?.characters.count > 0) {
Alamofire.request(.GET, "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=N&page_limit=10&page=1&apikey=\(key)").responseJSON() {
(responseData) -> Void in
print(responseData)
if let swiftyResponse = responseData.result.value {
let searches = Searches(JSONDecoder(swiftyResponse))
for search in searches.allSearches {
self.searchResults.append(search)
}
}
self.theatersTable.reloadData()
self.theatersTable.finishInfiniteScroll()
}
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.resultSearchController.active) {
return self.searchResults.count
} else {
return self.results.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
let titleLabel = cell.viewWithTag(1) as! UILabel
let yearLabel = cell.viewWithTag(2) as! UILabel
let durationLabel = cell.viewWithTag(3) as! UILabel
let posterImage = cell.viewWithTag(5) as! UIImageView
let starsTag = cell.viewWithTag(6) as! CosmosView
if (self.resultSearchController.active) {
titleLabel.text = searchResults[indexPath.row].titleMovie
yearLabel.text = searchResults[indexPath.row].yearMovie
durationLabel.text = searchResults[indexPath.row].durationMovie?.description
posterImage.sd_setImageWithURL(NSURL(string: searchResults[indexPath.row].posterMovie!))
starsTag.rating = searchResults[indexPath.row].ratingMovie!
starsTag.settings.updateOnTouch = false
} else {
titleLabel.text = results[indexPath.row].titleMovie
yearLabel.text = results[indexPath.row].yearMovie
durationLabel.text = results[indexPath.row].durationMovie?.description
posterImage.sd_setImageWithURL(NSURL(string: results[indexPath.row].posterMovie!))
starsTag.rating = results[indexPath.row].ratingMovie!
starsTag.settings.updateOnTouch = false
}
return cell
}
I also have some structs with information for the request tell me if you need something from that too.
Found the answer should have reloadData before the request.
func updateSearchResultsForSearchController(searchController: UISearchController) {
self.searchResults.removeAll(keepCapacity: false)
self.theatersTable.reloadData()//should have added this before the request
if (searchController.searchBar.text?.characters.count > 0) {
Alamofire.request(.GET, "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=\(searchController.searchBar.text!)&page_limit=10&page=1&apikey=\(key)").responseJSON() {
(responseData) -> Void in
if let swiftyResponse = responseData.result.value {
let searches = Searches(JSONDecoder(swiftyResponse))
for search in searches.allSearches {
self.searchResults.append(search)
}
}
self.theatersTable.reloadData()
self.theatersTable.finishInfiniteScroll()
}
}
}

passing object data between viewcontrollers in swift

I'm learning how to pass object data between viewcontrollers, and my source is:
firstly the class which represents the objects Flyer
class Flyer{
var title: String!
var desc: String!
var imageUrl: String!
init(dictionary: [String: AnyObject]) {
title = dictionary["title"] as? String
desc = dictionary["desc"] as? String
imageUrl = dictionary["imageUrl"] as? String
}
}
now the mainViewController class:
class MainViewController: UIViewController, UITableViewDataSource {
#IBOutlet var tableview:UITableView!
let apiClient = ApiClient()
var flyers: [Flyer]!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
apiClient.mainService.getList() { flyers, error in
if flyers != nil {
self.flyers = flyers
self.tableview.reloadData()
} else {
print("error: \(error)")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.flyers?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("mainObjectCell") as! MainTableViewCell
cell.mainObject = self.flyers?[indexPath.row]
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "detailSegue" {
let detailViewController = segue.destinationViewController as! DetailMainViewController
if let indexPath = tableView.indexPathForCell(sender as! MainTableViewCell) {
detailViewController.detailString = self.flyers?[indexPath.row]
}
}
}
}
the output of this class is an error, ambiguous use of tableview(_:numbersOfRowsInSection:) in the let indexPath
the detailViewController class:
class DetailMainViewController: UIViewController {
#IBOutlet weak var detailMainLabel: UILabel!
var detailString: String?
var receivedCellIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
detailMainLabel.text = detailString
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
I would like to know how to solve the error in the mainViewController class and how to pass the desc property of the flyer object to the detailViewController and show it in the label field

transition from collection view to table view

guys i have a problem when i want to change from uicollectionview to uitableview..
i have this storyboard, output and code in collection view like this
this is the storyboard, which is cell have identifier "cell"
(ignore the header section thou..)
and the output like
let reuseIdentifier = "Cell"
class SummaryViewController: UICollectionViewController, UICollectionViewDataSource, UICollectionViewDelegate {
#IBOutlet var collectionview: UICollectionView!
var photos:NSArray?
var items = NSMutableArray()
var TableData:Array< String > = Array < String >()
var json:String = ""
var arrayOfMenu: [ImageList] = [ImageList]()
var jsonObject: [String: AnyObject] = [String: AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
self.setUpMenu()
collectionview.dataSource = self
collectionview.delegate = self
NSLog("%d", items.count)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrayOfMenu.count //hitung banyak data pada array
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! UICollectionViewCell
let image = UIImage(named: items.objectAtIndex(indexPath.row) as! String)
let imageView = cell.viewWithTag(100) as! UIImageView
imageView.image = image
return cell
}
func setUpMenu() //membaca json pada setiap arraynya
{
var json: JSON = JSON (data: NSData())
DataManager.getactivityDataFromFileWithSuccess{ (data) -> Void in
json = JSON(data: data)
let results = json["results"]
for (var i = 0; i < json["Activity"].count; i++) {
if let icon: AnyObject = json["Activity"][i]["icon"].string {
self.items.addObject(icon)
dispatch_async(dispatch_get_main_queue(), {self.collectionView!.reloadData()})
var menu = ImageList(image: icon as! String)
self.arrayOfMenu.append(menu)
self.TableData.append(icon as! String)
}
}
}
}
but when i change it to table view, it gets some errors, like this
here is the storyboard with "cell" identifier same as before
but the output doesn't do the same, it becomes like this
why they won't appear like before (pic no 2)
and the code like this
class SummaryUITableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {
let reuseIdentifier = "Cell"
#IBOutlet var myTableView: UITableView!
var jsonObject: [String: AnyObject] = [String: AnyObject]()
var items = NSMutableArray()
var TableData:Array< String > = Array < String >()
var arrayOfMenu: [ImageList] = [ImageList]()
override func viewDidLoad() {
super.viewDidLoad()
self.myTableView.delegate = self
self.myTableView.dataSource = self
self.setUpMenu()
var curr:Array<Summarydata> = Array <Summarydata>()
var temp:Summarydata = Summarydata()
temp.bulan = "Agustus"
temp.setFood(Nutritionmenu.data)
curr.append(temp);
var data = JSONSerializer.toJson(curr)
println(data)
NSLog("%d", items.count)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: SummaryUITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as! SummaryUITableViewCell
var shortDate: String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMMM"
return dateFormatter.stringFromDate(NSDate())
}
cell.setCell(shortDate)
let image = UIImage(named: items.objectAtIndex(indexPath.row) as! String)
let imageView = cell.viewWithTag(100) as! UIImageView
imageView.image = image
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayOfMenu.count
}
func setUpMenu() //membaca json pada setiap arraynya
{
var json: JSON = JSON (data: NSData())
DataManager.getactivityDataFromFileWithSuccess{ (data) -> Void in
json = JSON(data: data)
let results = json["results"]
for (var i = 0; i < json["Activity"].count; i++) {
if let icon: AnyObject = json["Activity"][i]["icon"].string {
self.items.addObject(icon)
var menu = ImageList(image: icon as! String)
self.arrayOfMenu.append(menu)
self.TableData.append(icon as! String)
}
}
}
}
}
class SummaryUITableViewCell: UITableViewCell {
#IBOutlet weak var lblUnit: UILabel!
func setCell(lblUnit: String){
self.lblUnit.text = lblUnit
}
}
anyone can help?

Resources