我从 url 中获取数据作为 json
字符串。在我的代码中,titles
变量是我的url
图片的数组。
private let reuseIdentifier = "cell_supporters"
class SupportersCollectionViewController: UICollectionViewController {
var ids = [String]()
var titles = [String]()
@IBOutlet var collection_supporters: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collection_supporters.delegate = self
// Register cell classes
self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
getSupporters()
}
// MARK: UICollectionViewDataSource
// override func numberOfSections(in collectionView: UICollectionView) -> Int {
// // #warning Incomplete implementation, return the number of sections
// return 1
// }
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return self.titles.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! SupportersCollectionViewCell
print("Hello collectionView")
let url_img = URL(string: self.titles[indexPath.row])!
print(url_img)
cell.img_logo.af_setImage(
withURL: url_img
)
return cell
}
func getSupporters() {
RestApiManager.sharedInstance.getSupporters { (json: JSON) in
if let results = json.array {
for entry in results {
// print(entry["title"])
//self.ids.append(entry["id"].string!)
self.titles.append(entry["title"].string!)
}
print(self.titles.count)
DispatchQueue.main.async{
self.collection_supporters.reloadData()
}
}
}
}
}
在我的代码中:
print(self.titles.count) // it shows 5
但是:
print("Hello collectionView") // not show anything !
最佳答案
如果您为布局使用默认的 UICollectionViewFlowLayout
类,您可以尝试实现返回 collectionView
中每个项目大小的委托(delegate)方法。如果 UICollectionView
没有大小信息或它们为零,则它根本不会调用 cellForItemAt
dataSource 方法。
尝试添加这个:
extension SupportersCollectionViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 40, height: 40) // Return any non-zero size here
}
}
关于ios - uicollectionview 不快速显示单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42302408/