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 each category from a downloaded JSON #19

Open silviocolman opened 7 years ago

silviocolman commented 7 years ago

Good evening, I'm making an app that will organize my class schedules for college. I do it the following way I have a JSON in dropbox which has the data of all the subjects that are dictated in the week of Monday to Friday ordered already by hour of each class, my problem is the following one when downloading the JSON that contains all the subjects I compare said days and charge in a vector only the days that would have to load the first time of my cycle which would be the Monday day and what it does until now my code is to load all the data of the JSON in every day.

//UserService.swift
import UIKit
import Alamofire

extension MockData {

          static func index(completion: @escaping ([MockData]) -> Void) {

            Alamofire.request("https://www.dropbox.com/s/fem028u5ok95270/Clases.json?dl=1") .responseJSON { (response) in
            print(response)
            var users = [MockData]()
            if let objects = response.result.value {
                let json = objects as! NSDictionary
                let list = json["Horario"] as? [[String: AnyObject]]

            for object in list! {
                users.append(MockData(dictionary: object))
            }
            }
            completion(users)

        }

    }
}

Mi modelo de Datos

//MockData.swift
import UIKit

class MockData: NSObject {

      var id : String?
      var dia : DiasClases?
      var materia : String?
      var horario : String?
      var seccion : String?
      var profesor : String?
    //var aula : String?
    //var obs : String?
      var HorarioArray = [MockData]()

init(dictionary: [String: AnyObject]){

    self.id = dictionary["id"] as? String
    let d = dictionary["dia"] as? String
    switch d {
    case "Lunes"?:
        self.dia = .Lunes
    case "Martes"?:
        self.dia = .Martes
    case "Miercoles"?:
        self.dia = .Miercoles
    case "Jueves"?:
        self.dia = .Jueves
    case "Viernes"?:
        self.dia = .Viernes
    case "Sabado"?:
        self.dia = .Sabado
    default:
        print("ERROR")

    }
    self.materia = dictionary["materia"] as? String
    self.horario = dictionary["horario"] as? String
    self.seccion = dictionary["seccion"] as? String
    self.profesor = dictionary["profesor"] as? String
    //self.aula = dictionary["aula"] as? String
    //self.obs = dictionary["obs"] as? String

 }

}

enum DiasClases {
    case Lunes
    case Martes
    case Miercoles
    case Jueves
    case Viernes
    case Sabado

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

Mi NewViewController.swift el que se encarga de crearme todas las vistas necesarias

import UIKit

class NewsViewController: UIViewController, ACTabScrollViewDelegate, ACTabScrollViewDataSource {

    @IBOutlet weak var tabScrollView: ACTabScrollView!

    var contentViews: [UIView] = []
    var friends: [MockData] = []

  override func viewDidLoad() {
    super.viewDidLoad()
    print("Inicio de viewDidLoad en NewsViewController")
    // set ACTabScrollView, all the following properties are optional
       tabScrollView.defaultPage = 0
       tabScrollView.arrowIndicator = true
       tabScrollView.delegate = self
       tabScrollView.dataSource = self

    // crear vistas de contenido de "storyboard"
    let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
    for category in DiasClases.AllValues() {
        let vc = storyboard.instantiateViewController(withIdentifier: "ContentViewController") as! ContentViewController
        vc.category = category

        addChildViewController(vc) // no hay que olvidar, que es muy importante
        print("regreso a New")
        contentViews.append(vc.view)
        print("Termino la funcion viewDidload")

     }

    // aspecto de la barra de navegación conjunto
    if let navigationBar = self.navigationController?.navigationBar {
        print("Dentro del if de conf de barra de navegacion")
        navigationBar.isTranslucent = false
        navigationBar.tintColor = UIColor.white
        navigationBar.barTintColor = UIColor(red: 255.0 / 255, green: 255.0 / 255, blue: 255.0 / 255, alpha: 1)
        navigationBar.titleTextAttributes = NSDictionary(object: UIColor.red, forKey: NSForegroundColorAttributeName as NSCopying) as? [String : AnyObject]
        navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        navigationBar.shadowImage = UIImage()
    }
    UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
}

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

func tabScrollView(_ tabScrollView: ACTabScrollView, didScrollPageTo index: Int) {
    print("cambio de pagina con scroll")
}

// MARK: ACTabScrollViewDataSource
func numberOfPagesInTabScrollView(_ tabScrollView: ACTabScrollView) -> Int {
    print("numeros de paginas")
    return DiasClases.AllValues().count
}

func tabScrollView(_ tabScrollView: ACTabScrollView, tabViewForPageAtIndex index: Int) -> UIView {
    // crear una etiqueta
    print("Creando una Etiqueta")
    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: 255.0 / 255, blue: 255.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
    print("Etiqueta Creada")
    return label
}

func tabScrollView(_ tabScrollView: ACTabScrollView, contentViewForPageAtIndex index: Int) -> UIView {
    print("Dentro de la funcion tabScrollView de NewViewController")
    return contentViews[index]
  }
}

Y por ultimo mi contenedor de vista de tabla ContentViewController.swift

import UIKit

class ContentViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

  @IBOutlet weak var tableView: UITableView!

  var category: DiasClases? {
      didSet {
         print("Dentro de category")
         for news in friends {

             if (news.dia == category ) {
                friends.append(news)
                print(friends)
             }
          }
       }
   }
  var friends: [MockData] = []
  override func viewDidLoad() {
    super.viewDidLoad()
    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action:#selector(refresh),for: .valueChanged)
    print("Dentro de viewDidLoad en ContentViewController")
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 44
    tableView.delegate = self
    tableView.dataSource = self

    MockData.index { users in
        self.friends = users
        self.tableView.reloadData()

    }

    print("Fin de viewDidLoad en ContentViewController")
 }

func numberOfSections(in tableView: UITableView) -> Int {
    print("Numero de Secciones de la Tabla")
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print("Numero de filas")
    return friends.count
}

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

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

    // set the cell
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! ContentTableViewCell
    //cell.thumbnailImageView.image = UIImage(named: "thumbnail-\(news.id)")
    //cell.thumbnailImageView.layer.cornerRadius = 4
    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
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 0.1
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let view = UIView()
    view.backgroundColor = UIColor(red: 0.0 / 255, green: 0.0 / 255, blue: 0.0 / 255, alpha: 1.0)

    let label = UILabel()
    label.text = " "
    label.textColor = UIColor.white
    if #available(iOS 8.2, *) {
        label.font = UIFont.systemFont(ofSize: 17, weight: UIFontWeightThin)
    } else {
        label.font = UIFont.systemFont(ofSize: 17)
    }
    label.sizeToFit()
    label.frame.origin = CGPoint(x: 18, y: 13)

    view.addSubview(label)

    return view
}

 func refresh() {

 }

}

class ContentTableViewCell: UITableViewCell {

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

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

}

Please if you can see where I am wrong I would appreciate it too. Thank you so much!

saito-sv commented 6 years ago

@silviocolman tu pregunta fue ya se mucho tiempo, pero la verdad no entiendo que es lo que estas preguntando en realidad. @silviocolman I know your asked this question a while back but your I can't really understand what your question is. Are you trying to load the json into the tabs?

silviocolman commented 6 years ago

What I try to do is that on each day of the week only the corresponding schedules are loaded, but the only thing I have achieved is to load in the tableview all the data of my json file and I want to load it in each view of days of the week the corresponding schedule. thanks for answering