I have a plist that is an array containing hundreds of arrays, each containing 22 strings. How do I get the first string of each array in the plist?
I'm using collections and in cellForItemAt
I'm trying to get the first string of the arrays to show under each cell in a label.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Collections
// Set Image
cell.imageCell.image = UIImage(named: "image_\(indexPath.row)")
// Check NameLabel Switch Status
if savedSwitchStatus == true {
cell.labelCell.isHidden = false
cell.labelCell.text = (??) // <--------------
} else {
cell.labelCell.isHidden = true
}
return cell
}
I have 2 types of plists:
First plist has 1 array with multiple strings. Each string is a name that goes under the cells.
Second plist is an array of arrays, each array containing 22 strings. Here I need to get only the first string from each array to show under the cells.
You need to parse your plist into Array of Array of Strings i.e. [[String]].
func arrayFromPlist(plist:String) -> [[String]]? {
guard let fileUrl = Bundle.main.url(forResource: plist, withExtension: "plist"), let data = try? Data(contentsOf: fileUrl) else {
return nil
}
return try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [[String]]
}
Use above function to get the array and use the array as a datasource to tableview.
var datasourceArray:[[String]] {
didSet {
self.tableView.reloadData()
}
}
In your cellForRow:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Collections
// Set Image
cell.imageCell.image = UIImage(named: "image_\(indexPath.row)")
let strings = datasourceArray[indexPath.row]!
// Check NameLabel Switch Status
if savedSwitchStatus == true {
cell.labelCell.isHidden = false
cell.labelCell.text = strings.first
} else {
cell.labelCell.isHidden = true
}
return cell
}