Created
March 11, 2021 11:43
-
-
Save sp71/f81412a1c80386ca1f12ce183b0ca577 to your computer and use it in GitHub Desktop.
Format JSON into Label
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Line: Codable { | |
var punjabi: String | |
var translit: String | |
var english: String | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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