'How to populate CollectionView Horizontally with an Array Model that is coming from API
I am having a lot of difficulties dealing with setting up the CollectionView in the ViewController to populate the CollectionView Cells with the Model I have.
The CollectionView needs to be Horizontally, I tried setting it up like i did with tableView cells but it's a different world the one of the CollectionView since I can't work it out like tableView just a simple list since in CollectionView Horizontally it's in form of left-right not in a form of list
Any little help is really appreciated.
My Model:
struct connectedProperties: Decodable {
var StatusCode: Int
var Result: [connProperties]?
}
struct connProperties: Decodable {
let id: Int
let completeName, customerCode: String
}
View Controller:
class dashboardViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var CollectionView: UICollectionView!
var properties = connectedProperties(StatusCode: 0)
var propertiesNew = connectedProperties(StatusCode: 0)
override func viewDidLoad() {
super.viewDidLoad()
fetchAndReloadDataConnectedProperties()
CollectionView.delegate = self
CollectionView.dataSource = self
}
func fetchAndReloadDataConnectedProperties(){
APICallerGET.shared.connectedPropertiesOfAccount(for: APICallerGET.shared.token!) { [self] (result, error) in
switch result?.StatusCode {
case 0:
self.propertiesNew = result!
self.properties = self.propertiesNew
DispatchQueue.main.async {
self.dashboardTableView.reloadData()
}
case 1:
print("error")
default:
break
}
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return properties.Result?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "dashboardCollectionViewCell", for: indexPath) as? dashboardCollectionViewCell else { return UICollectionViewCell()}
let currentPropertie = properties.Result![indexPath.item]
cell.nameSurnameLabel?.text = currentPropertie.completeName
cell.containerForCell.layer.cornerRadius = CGFloat(3)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 185, height: 50)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
