transition from collection view to table view - ios

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?

Related

Load/Download image from SDWebimage and display in Custom tableView cell imageView

i already parsed other values but how will i show image to imageView i m already using SdWebImage in Swift.I want to show that in Bottom cell "detail" Below is my code
import UIKit
import SystemConfiguration
import MBProgressHUD
public struct Section {
var arrayDataTop: String
var arrayTerms: String
var qrImage:String
var collapsed: Bool
public init( arrayDataTop: String,qrImage: String ,arrayTerms: String, collapsed: Bool = false) {
self.arrayDataTop = arrayDataTop
self.qrImage = qrImage
self.arrayTerms = arrayTerms
self.collapsed = collapsed
}
}
class CollapsibleViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var tableViewCollapsible:UITableView!
#IBOutlet weak var listImage:UIImageView!
var nodatastr:String = "No Deal Found."
var dealIDCollapsible : String?
var dealDictCollapsible = [String: AnyObject]()
var parentNavigationController: UINavigationController?
private var loadingView:MBProgressHUD?
var sectionDataObj = [Section]()
override func viewDidLoad() {
super.viewDidLoad()
if (!self.isInternetAvailable()){
self.alertMessageShow(title: "No Internet Connection", message: "Make sure your device is connected to the internet.")
}
else{
if self.loadingView == nil {
self.loadingView = MBProgressHUD.showAdded(to: self.view, animated: true)
}
tableViewCollapsible.estimatedRowHeight = 100.0
tableViewCollapsible.layoutIfNeeded()
tableViewCollapsible.updateConstraintsIfNeeded()
tableViewCollapsible.tableFooterView = UIView()
self.listImageFetch()
dealFetchParticularListing()
}
}
func dealFetchParticularListing(){
let prs = [
"listing_id":dealIDCollapsible,//dealIDCollapsible,
"Deal_fetch_listing": "1" as String
]
Service.CreateDeal(prs as [String : AnyObject]?, onCompletion: { result in
let json = result as? NSDictionary
if let data = json as? [String:Any]{
if let err = data["status"] as? String, err == "success"{
if let data = data["result"] as? [Any]{
//
//fill your data in that local Section obj
//
var sectionDataObj = [Section]()
for sectionObj in data{
if let sectionObjVal = sectionObj as? [String:Any]{
if let qrcode = sectionObjVal["qrcode"] as? String{
if let tnc = sectionObjVal["tnc"] as? String{
if let deal_title = sectionObjVal["deal_title"] as? String{
let sectionValue = Section(arrayDataTop: deal_title, qrImage: qrcode, arrayTerms: tnc)
// access main objects/UIelement on main thread ONLY
sectionDataObj.append(sectionValue)
}
}
}
}
}
DispatchQueue.main.async { () -> Void in
self.sectionDataObj.removeAll()
//
//assign ur data in main sampleData(Section obj) then reload tableView with that data.
//
self.sectionDataObj = sectionDataObj
self.tableViewCollapsible.reloadData()
self.loadingView?.hide(true)
}
}
}
}
})
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Header
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "header") as! MyCellData
cell.lblDealTitle.text = sectionDataObj[indexPath.section].arrayDataTop
return cell
}
// Cell
let cell = tableView.dequeueReusableCell(withIdentifier: "detail") as! MyCellData
cell.lblTerm.text = sectionDataObj[indexPath.section].arrayTerms
// here i want to show image
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension//320.0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
let collapsed = !sectionDataObj[indexPath.section].collapsed
// Toggle collapse
sectionDataObj[indexPath.section].collapsed = collapsed
self.tableViewCollapsible.reloadSections([indexPath.section], with: .automatic)
}
}
}
class MyCellData:UITableViewCell{
#IBOutlet weak var lblDealTitle: UILabel!
#IBOutlet weak var dealimage: UIImageView!
#IBOutlet weak var lblTerm: UILabel!
#IBOutlet weak var qrCodeImage: UIImageView!
}
Plz help me with this.thanks in advance.All things are working properly i am able to see other details.Help will be appreciated.Plz help me i m struggling with this issue.
update ur tableView cellForRowAt like so to show an image or ur cell from ur sectionDataObj
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Header
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "header") as! MyCellData
cell.lblDealTitle.text = sectionDataObj[indexPath.section].arrayDataTop
return cell
}
// Cell
let cell = tableView.dequeueReusableCell(withIdentifier: "detail") as! MyCellData
cell.lblTerm.text = sectionDataObj[indexPath.section].arrayTerms
let imgUrl = sectionDataObj[indexPath.section]. qrImage
cell.qrCodeImage.sd_setImage(with: URL(string:imgUrl), completed: nil)
return cell
}

Value in JSON does not display in tableviewcell custom

Can't display data in TableViewCell.Data reports of events, but the when you open the array "sports" display the data in cels no.The display of the title occurs and the transfer is ended...
This is my json code...
Event.swift
import UIKit
struct Event {
let match : String
let forecast : String
let data : String
let image : UIImage
var sports : [Sport]
init (match : String, forecast : String, data: String, image : UIImage, sports : [Sport]) {
self.match = match
self.forecast = forecast
self.data = data
self.image = image
self.sports = sports
}
static func eventsFromBundle ()-> [Event] {
var events = [Event] ()
guard let url = Bundle.main.url(forResource: "events", withExtension: "json") else {
return events
}
do {
let data = try Data(contentsOf: url)
guard let rootObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String : Any] else {
return events
}
guard let eventObjects = rootObject["events"] as? [[String: AnyObject]] else {
return events
}
for eventObject in eventObjects {
if let match = eventObject["match"] as? String,
let forecast = eventObject["forecast"] as? String,
let data = eventObject["data"] as? String,
let imageName = eventObject["image"] as? String,
let image = UIImage(named: imageName),
let sportsObject = eventObject["sports"] as? [[String : String]]{
var sports = [Sport]()
for sportObject in sportsObject {
if let nameTitle = sportObject["name"] ,
let titleName = sportObject["image"],
let titleImage = UIImage(named: titleName + ".jpg"),
let prognozLabel = sportObject["prognoz"],
let obzor = sportObject["obzor"] {
sports.append(Sport(name: nameTitle, prognoz: prognozLabel, image: titleImage, obzor: obzor, isExpanded: false))
}
}
let event = Event(match: match, forecast: forecast, data: data, image: image, sports: sports)
events.append(event)
}
}
} catch {
return events
}
return events
}
}
import UIKit
class SportViewController: BaseViewController {
var events = Event.eventsFromBundle ()
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
addSlideMenuButton()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(forName: .UIContentSizeCategoryDidChange, object: .none, queue: OperationQueue.main) { [weak self] _ in
self?.tableView.reloadData()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? SportDetailViewController,
let indexPath = tableView.indexPathForSelectedRow {
destination.selectedEvent = events[indexPath.row]
}
}
}
extension SportViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return events.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellMatch", for: indexPath) as! SportTableViewCell
let event = events[indexPath.row]
cell.matchLabel.text = event.match
cell.imageMatch.image = event.image
cell.forecastLabel.text = event.forecast
cell.dataLabel.text = event.data
cell.matchLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
cell.forecastLabel.font = UIFont.preferredFont(forTextStyle: .callout)
return cell
}
}
Her is the controller.SportDetailViewController.swift
import UIKit
class SportDetailViewController: UIViewController {
var selectedEvent : Event!
let obzorText = "Select for more info >"
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
title = selectedEvent.match
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 300
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
}
extension SportDetailViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return selectedEvent.sports.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : SportDetailTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cellMatch", for: indexPath) as! SportDetailTableViewCell
let sport = selectedEvent.sports[indexPath.row]
cell.nameTitle.text = sport.name
cell.titleImage.image = sport.image
cell.prognozLabel.text = sport.prognoz
cell.selectionStyle = .none
cell.nameTitle.backgroundColor = UIColor.darkGray
cell.backgroundColor = UIColor.red
cell.obzorText.text = sport.isExpanded ? sport.obzor : obzorText
cell.obzorText.textAlignment = sport.isExpanded ? .left : .center
return cell
}
}
extension SportDetailViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? SportDetailTableViewCell else { return }
var sport = selectedEvent.sports[indexPath.row]
sport.isExpanded = !sport.isExpanded
selectedEvent.sports[indexPath.row] = sport
cell.obzorText.text = sport.isExpanded ? sport.obzor : obzorText
cell.obzorText.textAlignment = sport.isExpanded ? .left : .center
tableView.beginUpdates()
tableView.endUpdates()
tableView.scrollToRow(at: indexPath, at: .top, animated: true)
}
}
all these methods have tried: tableview.datasource = self , tableview.delegate = self и reloadData().....in viewDidLoad.
Delete this init from your struct: (because struct gets free initializer)
init (match : String, forecast : String, data: String, image : UIImage, sports : [Sport]) {
self.match = match
self.forecast = forecast
self.data = data
self.image = image
self.sports = sports
}
Now, your var events won't be populated as you are calling method in class scope. So change this:
class SportViewController: BaseViewController {
var events = Event.eventsFromBundle ()
...
...
}
to
class SportViewController: BaseViewController {
var events = [Event]()
...
...
override func viewDidLoad() {
super.viewDidLoad()
addSlideMenuButton()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
events = Event().eventsFromBundle()
}
...
...
}
This should solve your problem.

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()
}
}
}

UICollectionView- How to add object on every cells?

how to make this become looks like iPhone gallery (if the data meets the end, i want to add the label which is shows the month) and make it repeatable
it become looks like this
i've tried every objects and insert to uicollectionview, but it doesn't appear at all..is there any way to help?
here is my code
import UIKit
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]()
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 (index: String, subJson: JSON) in 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)
}
}
}
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView
{
let header = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "headersection", forIndexPath: indexPath) as! UICollectionReusableView
return header
}
}

How can I pass the value from a view to another view in 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()
}
}

Resources