Skip to content

Instantly share code, notes, and snippets.

@sp71
Created March 11, 2021 11:43
Show Gist options
  • Save sp71/f81412a1c80386ca1f12ce183b0ca577 to your computer and use it in GitHub Desktop.
Save sp71/f81412a1c80386ca1f12ce183b0ca577 to your computer and use it in GitHub Desktop.
Format JSON into Label
import UIKit
class FileManager {
static func decodeJSON<T: Decodable>(fileName: String?, subdirectory: String?) -> T? {
guard let filename = fileName else { return nil }
if filename.isEmpty { return nil }
let decoder = JSONDecoder()
guard
let url = Bundle.main.url(forResource: filename, withExtension: "json", subdirectory: subdirectory),
let data = try? Data(contentsOf: url),
let decodedObject = try? decoder.decode(T.self, from: data)
else {
return nil
}
return decodedObject
}
}
class Line: Codable {
var punjabi: String
var translit: String
var english: String
}
class ViewController.: UICollectionViewDataSource, UICollectionViewDelegate {
var lineList = [Line]()
override func viewDidLoad() {
super.viewDidLoad()
guard let lineList: [Line] = FileManager.decodeJSON(fileName: "myfile", subdirectory: "rootFolder") else {
print("Error! loading file")
return
}
self.lineList = lineList
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return lineList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeue(ReadingCollectionViewCell.self, indexPath) // custom extension generic dequeue
let line = lineList[indexPath.row]
// ReadingCollectionViewCell contains all your labels & buttons. Use the line object to setup each UI element
cell.setup(line: line)
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment