无法在我的 collectionView 中显示来自数组(JSON)的数据
Posted
技术标签:
【中文标题】无法在我的 collectionView 中显示来自数组(JSON)的数据【英文标题】:Cant display data from array(JSON) in my collectionView 【发布时间】:2019-06-09 18:59:48 【问题描述】:我是 Swift 的新人(学习了几个星期),对我的英语感到抱歉。我不知道如何避免检查方法“cellForItemAt indexPath”。我尝试使用 refreshControl 但它不起作用。我在“let arry = arrayOfData[indexPath.row] //
class ViewController: UIViewController
@IBOutlet weak var collectionView: UICollectionView!
private var isRefreshing = true
var arrayOfData = [GettingMoney]()
override func viewDidLoad()
super.viewDidLoad()
let refreshControl = UIRefreshControl()
refreshControl.tintColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
collectionView.refreshControl = refreshControl
collectionView.refreshControl?.beginRefreshing()
fetchData()
collectionView.dataSource = self
collectionView.delegate = self
func fetchData ()
let url = "SOMEAPI"
guard let urlString = URL(string: url) else return
URLSession.shared.dataTask(with: urlString) (data, _, _) in
guard let data = data else return
do
let getData = try JSONDecoder().decode(GettingMoney.self, from: data)
print("getSomeData")
DispatchQueue.main.async
self.arrayOfData = [getData]
self.collectionView?.reloadData()
self.collectionView.refreshControl?.endRefreshing()
print("reload Data")
catch
print("Its a error")
.resume()
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
return 3
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCellId", for: indexPath) as? CollectionViewCell
let arry = arrayOfData[indexPath.row] // <-- here is got error: Fatal error: Index out of range
print("is Ok")
cell.currectCurrency.text = "\(arry.USD))"
print(arrayOfData)
return cell
return UICollectionViewCell()
【问题讨论】:
【参考方案1】:更新numberOfItemsInSections
如下,
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
return self.arrayOfData.count
【讨论】:
以上是关于无法在我的 collectionView 中显示来自数组(JSON)的数据的主要内容,如果未能解决你的问题,请参考以下文章
在tableView中单击不同行后在collectionView中显示不同的数组