azurechen / ACTabScrollView

A fancy Menu and Pager UI extends UIScrollView with elegant, smooth and synchronized scrolling tabs.
MIT License
115 stars 35 forks source link

Load array data downloaded from server #14

Closed silviocolman closed 7 years ago

silviocolman commented 7 years ago

@azurechen How can I adapt your API to load the data of the views from a json ?, I already have the json downloaded and in converted to an array what I would like to know is how to load them in all categories. I would appreciate your response! Regards!

thihaaung6245 commented 7 years ago

@silviocolman , I assume your data are loaded inside model object array. So, before creating view pager and each view, you can add here

let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())

// use for loop if you are going to use same controller for different pages
for i in 0 ..< /* number of pages */ {
      // here you instantiate your viewcontroller instance
      let vc = storyboard.instantiateViewControllerWithIdentifier("ContentViewController") as! ContentViewController 
      // create "data" object array at your view controller and assign your download json object into that "data" array
      vc.data = yourdata[i]

      addChildViewController(vc)
      contentViews.append(vc.view)
}

If you are going to use different controller, just comment "for loop"

let vc1 = storyboard.instantiateViewControllerWithIdentifier("ContentViewController") as! ContentViewController 
vc1.data = yourdata[2].list
addChildViewController(vc1)
contentViews.append(vc1.view)
let vc2 = storyboard.instantiateViewControllerWithIdentifier("ContentViewController") as! ContentViewController 
vc2.data = yourdata[2].list
addChildViewController(vc2)
contentViews.append(vc2.view)
silviocolman commented 7 years ago

@htarwara6245 I appreciate your help. I do not understand very well how to do it, could you help me by assuming that the array NewArray [category] is downloaded from a Json?

silviocolman commented 7 years ago

simulator screen shot 7 may 2017 14 48 26 My json contains day, schedule and subject. The day I charge it at the top, the schedules and matter in the table view what happens is that every day of the week is loaded my complete json without respecting the days that problem how could I solve?

azurechen commented 7 years ago

Could you paste your source code here and describe what effect you really expect?

silviocolman commented 7 years ago

"MockData.swift"

import UIKit
 class MockData {
                                 static var newsArray: [Clases] = ClasesArray
                              }
     enum DiasClases: String {
     case Lunes
     case Martes
     case Miercoles
     case Jueves
     case Viernes
     case Sabado

 static func allValues() -> [DiasClases] {
    return [Lunes, Martes, Miercoles, Jueves, Viernes, Sabado]
  }
}

func fromDictionary(dictionary: [String: AnyObject]) -> [Clases]
{
print("Dentro de la funcion formDictionary")
var clases = [Clases]()
let list = dictionary["Horario"] as? [[String: AnyObject]]

list?.forEach({ (listItem) in
    let dia = listItem["dia"] as? String
    let clase = Clases(id: (listItem["id"] as? String)! ,
                       dia: DiasClases(rawValue: dia!)!,
                       horario: (listItem["horario"] as? String)! ,
                       materia: (listItem["materia"] as? String)! ,
                       profesor: (listItem["profesor"] as? String)!,
                       seccion: (listItem["seccion"] as? String)!)
    clases.append(clase)
})
return clases
}

struct Clases {
                          var id: String
                          var dia: DiasClases
                          var horario: String
                          var materia: String
                          var profesor: String
                          var seccion: String
                      }

"ContentViewController.swift"

import UIKit

 class ContentViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

var category: DiasClases? {
    didSet {
        for news in MockData.newsArray {
            if (news.dia == category) {
                newsArray.append(news)
            }
        }
    print(newsArray)
    }
}
var newsArray: [Clases] = []

override func viewDidLoad() {
    super.viewDidLoad()

    print("Dentro del viewDidLoad de ContentViewController")

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 44
    tableView.delegate = self
    tableView.dataSource = self
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return newsArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    print("Dentro de cellForRowAt")

    let news = newsArray[(indexPath as NSIndexPath).row]

    // set the cell
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! ContentTableViewCell

    cell.titleLabel.text = news.materia
    cell.categoryLabel.text = String(describing: news.horario)
    cell.categoryView.layer.backgroundColor = UIColor.white.cgColor
    cell.categoryView.layer.cornerRadius = 4
    cell.categoryView.layer.borderWidth = 1
    cell.categoryView.layer.borderColor = UIColor(red: 238.0 / 255, green: 238.0 / 255, blue: 238.0 / 255, alpha: 1.0).cgColor

    return cell
}

}

class ContentTableViewCell: UITableViewCell {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var categoryView: UIView!
   @IBOutlet weak var categoryLabel: UILabel!

   override func awakeFromNib() {
    self.selectionStyle = .none
   }

 }

"ClasesViewController.swift"

 import UIKit

var ClasesArray: [Clases] = []

class ClasesViewController: UIViewController, ACTabScrollViewDelegate, ACTabScrollViewDataSource {

    @IBOutlet weak var tabScrollView: ACTabScrollView!

    var contentViews: [UIView] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        print("Dentro del viewDidLoad de ClasesViewController")

        // set ACTabScrollView, all the following properties are optional
        tabScrollView.defaultPage = 0
        tabScrollView.arrowIndicator = true
        //        tabScrollView.tabSectionHeight = 40
        //        tabScrollView.tabSectionBackgroundColor = UIColor.whiteColor()
        //        tabScrollView.contentSectionBackgroundColor = UIColor.whiteColor()
        //        tabScrollView.tabGradient = true
        //        tabScrollView.pagingEnabled = true
        //        tabScrollView.cachedPageLimit = 3

        tabScrollView.delegate = self
        tabScrollView.dataSource = self

        // create content views from storyboard
        let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        for category in DiasClases.allValues() {

            print("Dentro del For de Category")

            let vc = storyboard.instantiateViewController(withIdentifier: "ContentViewController") as! ContentViewController
            vc.category = category

            addChildViewController(vc) // don't forget, it's very important
            contentViews.append(vc.view)
            print(category)
        }

    print("Fin del viewDidLoad de ClasesViewController")
    }

    // MARK: ACTabScrollViewDelegate
    func tabScrollView(_ tabScrollView: ACTabScrollView, didChangePageTo index: Int) {
        print(index)
    }

    func tabScrollView(_ tabScrollView: ACTabScrollView, didScrollPageTo index: Int) {
    }

    // MARK: ACTabScrollViewDataSource
    // Funcion para definir la cantidad de paginas 

    func numberOfPagesInTabScrollView(_ tabScrollView: ACTabScrollView) -> Int {
        return DiasClases.allValues().count
    }

  // Funcion para Rellenar la vista de indice de las paginas

    func tabScrollView(_ tabScrollView: ACTabScrollView, tabViewForPageAtIndex index: Int) -> UIView {
        // create a label
        let label = UILabel()
        label.text = String(describing: DiasClases.allValues()[index]).uppercased()
        if #available(iOS 8.2, *) {
            label.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightThin)
        } else {
            label.font = UIFont.systemFont(ofSize: 16)
        }
        label.textColor = UIColor(red: 255.0 / 255, green: 0.0 / 255, blue: 0.0 / 255, alpha: 1)
        label.textAlignment = .center

        // if the size of your tab is not fixed, you can adjust the size by the following way.
        label.sizeToFit() // resize the label to the size of content
        label.frame.size = CGSize(width: label.frame.size.width + 28, height: label.frame.size.height + 36) // add some paddings

        return label
    }
 // Funcion para poder cargar las vistas en el content view

    func tabScrollView(_ tabScrollView: ACTabScrollView, contentViewForPageAtIndex index: Int) -> UIView {

        print("Dentro de ContentViewForPageAtIndex")
        return contentViews[index]

    }
}

My file Principal

 import UIKit

import Alamofire

class FiunappViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    Alamofire.request("https://www.dropbox.com/s/xsquxokz44p7i59/Clases.json?dl=1") .responseJSON { response in // 1
        //print(response.request)  // original URL request
        //print(response.response) // URL response
        //print(response.data)     // server data
        //print(response.result)   // result of response serialization
        if  let JSON = response.result.value {
            let json = JSON as! NSDictionary
            //print(json)
            ClasesArray = fromDictionary(dictionary: json as! [String : AnyObject])

        }
        print(ClasesArray)
    } 
 }

 override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
 }
} 

What I want is that when downloading my Json with the class schedules I locate it on each day corresponding to being able to show the subjects per day. When I execute like this the code gives me the following error

captura de pantalla 2017-05-08 a las 00 59 02

thihaaung6245 commented 7 years ago

@silviocolman , please format you code correctly else I can't focus enough. Or sharing example project of what you experiencing will be a lot helpful to us. Your json was download from dropbox anyway. So, share us so we can help you more quickly.

silviocolman commented 7 years ago

@htarwara6245 , There, modify what you asked for

azurechen commented 7 years ago

Hey, @silviocolman looks like you are already able to assign categories to differents view controller. Now you only needs to do is load data inside the ContentViewController and reload the tableView.

var category: DiasClases? {
    didSet {
        Alamofire.request("https://www.dropbox.com/s/xsquxokz44p7i59/Clases.json?dl=1") .responseJSON { response in
            if  let JSON = response.result.value {
                let json = JSON as! NSDictionary
                self.newArray = fromDictionary(dictionary: json as! [String : AnyObject])
                tableView.reloadData()
            }
        } 
    }
}
silviocolman commented 7 years ago

@azurechen , I appreciate your help, but even with that code does not work the application hangs simulator screen shot 9 may 2017 02 04 48

azurechen commented 7 years ago

If there is no data, you should check your JSON data first. You can paste the response of Alamofire responseJSON. We can try to figure out the problem.

silviocolman commented 7 years ago

captura de pantalla 2017-05-09 a las 23 25 52

azurechen commented 7 years ago

did you check the length and contents of your self.newArray? use debugger not print.

silviocolman commented 7 years ago

@azurechen How to use the debugger because I do not quite understand what you ask me to do. I would appreciate your response.

azurechen commented 7 years ago

add a breakpoint at any lines you want to see the status. and your app will pause at this line.

silviocolman commented 7 years ago

@azurechen What is discovered thanks to the debugger is that it remains in an infinite loop within the function captura de pantalla 2017-07-02 a la s 16 41 24

azurechen commented 7 years ago

I can't figure out what caused the infinite loop by just an image. Add a breakpoint and trace the call stack.

If you are a beginner of Xcode. Read the document and learn how to use the debugger. https://developer.apple.com/library/content/documentation/DeveloperTools/Conceptual/debugging_with_xcode/chapters/debugging_tools.html