Anonymous
Установите правильную высоту для фонового представления раздела в горизонтальном представлении коллекции.
Сообщение
Anonymous » 29 май 2024, 16:10
Я пробую представления современных коллекций с помощью приведенного ниже кода.
Единственная проблема в этом коде — высота фона раздела заполняется из последнего элемента. Если я продолжаю прокручивать представление коллекции по вертикали, это работает правильно.
Код: Выделить всё
class SectionDecorationViewController: UIViewController {
static let sectionBackgroundDecorationElementKind = "section-background-element-kind"
var currentSnapshot: NSDiffableDataSourceSnapshot! = nil
var dataSource: UICollectionViewDiffableDataSource! = nil
var collectionView: UICollectionView! = nil
var currentSelection: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Section Background Decoration View"
configureHierarchy()
configureDataSource()
}
}
extension SectionDecorationViewController {
/// - Tag: Background
func createLayout() -> UICollectionViewLayout {
let sectionProvider = { [weak self] (sectionIndex: Int,
layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in
guard let self = self else { return nil }
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
heightDimension: .absolute(44))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
// Get the number of items in the section
let itemCount = self.currentSnapshot.numberOfItems(inSection: sectionIndex)
// Custom group height based on the number of items
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
heightDimension: .absolute(CGFloat(itemCount) * 44))
let group = NSCollectionLayoutGroup.vertical(layoutSize: groupSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
section.orthogonalScrollingBehavior = .paging
section.interGroupSpacing = 0 // Remove inter-group spacing
section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0) // Remove content insets
// Add the background decoration item
let sectionBackgroundDecoration = NSCollectionLayoutDecorationItem.background(
elementKind: SectionDecorationViewController.sectionBackgroundDecorationElementKind)
section.decorationItems = [sectionBackgroundDecoration]
return section
}
let config = UICollectionViewCompositionalLayoutConfiguration()
config.scrollDirection = .horizontal
config.interSectionSpacing = 0
let layout = UICollectionViewCompositionalLayout(
sectionProvider: sectionProvider, configuration: config)
layout.register(
SectionBackgroundDecorationView.self,
forDecorationViewOfKind: SectionDecorationViewController.sectionBackgroundDecorationElementKind)
return layout
}
}
extension SectionDecorationViewController {
func configureHierarchy() {
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createLayout())
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
collectionView.backgroundColor = .systemBackground
view.addSubview(collectionView)
collectionView.delegate = self
}
func configureDataSource() {
let cellRegistration = UICollectionView.CellRegistration { (cell, indexPath, identifier) in
// Populate the cell with our item description.
cell.label.text = "\(indexPath.section),\(indexPath.item)"
}
dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) {
(collectionView: UICollectionView, indexPath: IndexPath, identifier: Int) -> UICollectionViewCell? in
// Return the cell.
return collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: identifier)
}
// initial data
let itemsPerSection = 5
let sections = Array(0..
Подробнее здесь: [url]https://stackoverflow.com/questions/78549115/set-correct-height-to-section-background-view-in-horizontal-collectionview[/url]
1716988219
Anonymous
Я пробую представления современных коллекций с помощью приведенного ниже кода. Единственная проблема в этом коде — высота фона раздела заполняется из последнего элемента. Если я продолжаю прокручивать представление коллекции по вертикали, это работает правильно. [code]class SectionDecorationViewController: UIViewController { static let sectionBackgroundDecorationElementKind = "section-background-element-kind" var currentSnapshot: NSDiffableDataSourceSnapshot! = nil var dataSource: UICollectionViewDiffableDataSource! = nil var collectionView: UICollectionView! = nil var currentSelection: Bool = false override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Section Background Decoration View" configureHierarchy() configureDataSource() } } extension SectionDecorationViewController { /// - Tag: Background func createLayout() -> UICollectionViewLayout { let sectionProvider = { [weak self] (sectionIndex: Int, layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in guard let self = self else { return nil } let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(44)) let item = NSCollectionLayoutItem(layoutSize: itemSize) // Get the number of items in the section let itemCount = self.currentSnapshot.numberOfItems(inSection: sectionIndex) // Custom group height based on the number of items let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(CGFloat(itemCount) * 44)) let group = NSCollectionLayoutGroup.vertical(layoutSize: groupSize, subitems: [item]) let section = NSCollectionLayoutSection(group: group) section.orthogonalScrollingBehavior = .paging section.interGroupSpacing = 0 // Remove inter-group spacing section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0) // Remove content insets // Add the background decoration item let sectionBackgroundDecoration = NSCollectionLayoutDecorationItem.background( elementKind: SectionDecorationViewController.sectionBackgroundDecorationElementKind) section.decorationItems = [sectionBackgroundDecoration] return section } let config = UICollectionViewCompositionalLayoutConfiguration() config.scrollDirection = .horizontal config.interSectionSpacing = 0 let layout = UICollectionViewCompositionalLayout( sectionProvider: sectionProvider, configuration: config) layout.register( SectionBackgroundDecorationView.self, forDecorationViewOfKind: SectionDecorationViewController.sectionBackgroundDecorationElementKind) return layout } } extension SectionDecorationViewController { func configureHierarchy() { collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createLayout()) collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionView.backgroundColor = .systemBackground view.addSubview(collectionView) collectionView.delegate = self } func configureDataSource() { let cellRegistration = UICollectionView.CellRegistration { (cell, indexPath, identifier) in // Populate the cell with our item description. cell.label.text = "\(indexPath.section),\(indexPath.item)" } dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) { (collectionView: UICollectionView, indexPath: IndexPath, identifier: Int) -> UICollectionViewCell? in // Return the cell. return collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: identifier) } // initial data let itemsPerSection = 5 let sections = Array(0.. Подробнее здесь: [url]https://stackoverflow.com/questions/78549115/set-correct-height-to-section-background-view-in-horizontal-collectionview[/url]