Я новичок в языке программирования Swift, у меня возникла проблема с отображением данных в ячейке CollectionView, хотя я правильно зарегистрировал ячейку с правильным идентификатором ячейки, а также получаю правильные данные в ответе API, но она отображает пустой UITableCell() , ниже приведен код viewController
import UIKit
import Combine
import PureLayout
class SchoolListCollectionViewController: UIViewController {
private let schoolsViewModel : SchoolsViewModel = SchoolsViewModel()
private var cancellables = Set()
private var collectionView: UICollectionView?
private struct Constants{
static let cellIdentifier: String = "schoolCell"
static let cellHeight: CGFloat = 100
static let sectionHeaderIdentifier: String = "sectionHeader"
static let sectionHeight: CGFloat = 50
}
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
setupBinders()
schoolsViewModel.getSchools()
let titleStr = "schools.title".localized()
}
private func setupCollectionView(){
let collectionViewLayout = UICollectionViewFlowLayout()
collectionViewLayout.itemSize = CGSize(width: view.frame.size.width, height: Constants.cellHeight)
// collectionViewLayout.headerReferenceSize = CGSize(width: view.frame.size.width, height: Constants.sectionHeight)
collectionViewLayout.scrollDirection = .vertical
collectionView = UICollectionView(frame: view.frame, collectionViewLayout: collectionViewLayout)
guard let collectionView = collectionView else {
return
}
view.addSubview(collectionView)
collectionView.autoPinEdgesToSuperviewEdges()
collectionView.backgroundColor = .white
collectionView.alwaysBounceVertical = true
//setup & customise flow layout
collectionView.register(SchoolCollectionViewCell.self, forCellWithReuseIdentifier: Constants.cellIdentifier)
collectionView.delegate = self
collectionView.dataSource = self
}
private func setupBinders(){
schoolsViewModel.$schools
.receive(on: RunLoop.main) //to run it on main thread
.sink{ [weak self] schools in
if let schools = schools,
!schools.isEmpty {
print("retrived \(schools.count) schools")
self?.collectionView?.reloadData()
}
}
.store(in: &cancellables)
schoolsViewModel.$error
.receive(on: RunLoop.main)
.sink{ [weak self] error in
if let error = error {
let alert = UIAlertController(title: "Error", message: "Could not retrieve schools: \(error.localizedDescription)", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default)
alert.addAction(action)
self?.present(alert, animated: true)
}
}
.store(in: &cancellables)
}
}
extension SchoolListCollectionViewController: UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return schoolsViewModel.schools!.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.cellIdentifier, for: indexPath) as? SchoolCollectionViewCell else {
return UICollectionViewCell()
}
let school = schoolsViewModel.schools?[indexPath.item]
cell.populate(school!)
return cell
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
}
Подробнее здесь: https://stackoverflow.com/questions/786 ... nview-cell
Невозможно отобразить данные в ячейке CollectionView. ⇐ IOS
Программируем под IOS
-
Anonymous
1719005458
Anonymous
Я новичок в языке программирования Swift, у меня возникла проблема с отображением данных в ячейке CollectionView, хотя я правильно зарегистрировал ячейку с правильным идентификатором ячейки, а также получаю правильные данные в ответе API, но она отображает пустой UITableCell() , ниже приведен код viewController
import UIKit
import Combine
import PureLayout
class SchoolListCollectionViewController: UIViewController {
private let schoolsViewModel : SchoolsViewModel = SchoolsViewModel()
private var cancellables = Set()
private var collectionView: UICollectionView?
private struct Constants{
static let cellIdentifier: String = "schoolCell"
static let cellHeight: CGFloat = 100
static let sectionHeaderIdentifier: String = "sectionHeader"
static let sectionHeight: CGFloat = 50
}
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
setupBinders()
schoolsViewModel.getSchools()
let titleStr = "schools.title".localized()
}
private func setupCollectionView(){
let collectionViewLayout = UICollectionViewFlowLayout()
collectionViewLayout.itemSize = CGSize(width: view.frame.size.width, height: Constants.cellHeight)
// collectionViewLayout.headerReferenceSize = CGSize(width: view.frame.size.width, height: Constants.sectionHeight)
collectionViewLayout.scrollDirection = .vertical
collectionView = UICollectionView(frame: view.frame, collectionViewLayout: collectionViewLayout)
guard let collectionView = collectionView else {
return
}
view.addSubview(collectionView)
collectionView.autoPinEdgesToSuperviewEdges()
collectionView.backgroundColor = .white
collectionView.alwaysBounceVertical = true
//setup & customise flow layout
collectionView.register(SchoolCollectionViewCell.self, forCellWithReuseIdentifier: Constants.cellIdentifier)
collectionView.delegate = self
collectionView.dataSource = self
}
private func setupBinders(){
schoolsViewModel.$schools
.receive(on: RunLoop.main) //to run it on main thread
.sink{ [weak self] schools in
if let schools = schools,
!schools.isEmpty {
print("retrived \(schools.count) schools")
self?.collectionView?.reloadData()
}
}
.store(in: &cancellables)
schoolsViewModel.$error
.receive(on: RunLoop.main)
.sink{ [weak self] error in
if let error = error {
let alert = UIAlertController(title: "Error", message: "Could not retrieve schools: \(error.localizedDescription)", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default)
alert.addAction(action)
self?.present(alert, animated: true)
}
}
.store(in: &cancellables)
}
}
extension SchoolListCollectionViewController: UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return schoolsViewModel.schools!.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.cellIdentifier, for: indexPath) as? SchoolCollectionViewCell else {
return UICollectionViewCell()
}
let school = schoolsViewModel.schools?[indexPath.item]
cell.populate(school!)
return cell
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/78654497/not-able-to-display-data-on-collectionview-cell[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия