Установите правильную высоту для фонового представления раздела в горизонтальном представлении коллекции.IOS

Программируем под IOS
Ответить
Anonymous
 Установите правильную высоту для фонового представления раздела в горизонтальном представлении коллекции.

Сообщение Anonymous »

Я пробую представления современных коллекций с помощью приведенного ниже кода.
Единственная проблема в этом коде — высота фона раздела заполняется из последнего элемента. Если я продолжаю прокручивать представление коллекции по вертикали, это работает правильно.

Код: Выделить всё

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]
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»