https://drive.google.com/file/d/1A8FPnp ... sp=sharing
В этом случае, когда я прокручиваю ячейки представления коллекции, фоновое изображение также прокручивается.
Я использую этот код для создания UICollectionViewCompositionalLayout:
Свойства
Код: Выделить всё
var collectionView: UICollectionView!
var dataSource: UICollectionViewDiffableDataSource?
let sections = Bundle.main.decode([Section].self, from: "section.json")
Код: Выделить всё
override func viewDidLoad() {
super.viewDidLoad()
createCollectionView()
}
Код: Выделить всё
func createDataSource() {
dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) { collectionView, indexPath, item in
switch self.sections[indexPath.section].identifier {
case "carouselCell": return self.configure(CarouselCell.self, with: item, for: indexPath)
default: return self.configure(CarouselCell.self, with: item, for: indexPath)
}
}
}
func configure(_ cellType: T.Type, with item: Item, for indexPath: IndexPath) -> T {
guard let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: cellType.reuseIdentifier,
for: indexPath) as? T else {
fatalError("Unable to dequeue \(cellType)")
}
cell.configure(with: item)
return cell
}
func reloadData() {
var snapshot = NSDiffableDataSourceSnapshot()
snapshot.appendSections(sections)
for section in sections { snapshot.appendItems(section.item, toSection: section) }
dataSource?.apply(snapshot)
}
Код: Выделить всё
func createCollectionView() {
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createCompositionalLayout())
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
collectionView.backgroundColor = .gray
collectionView.isScrollEnabled = false
view.addSubview(collectionView)
collectionView.register(CarouselCell.self, forCellWithReuseIdentifier: CarouselCell.reuseIdentifier)
createDataSource()
reloadData()
}
func createCompositionalLayout() -> UICollectionViewLayout {
let layout = UICollectionViewCompositionalLayout { sectionIndex, layoutEnvironment in
let section = self.sections[sectionIndex]
switch section.identifier {
case "сarouselCell": return self.carouselSection(using: section)
default: return self.carouselSection(using: section)
}
}
let config = UICollectionViewCompositionalLayoutConfiguration()
config.interSectionSpacing = 20
layout.configuration = config
return layout
}
Код: Выделить всё
func carouselSection(using section: Section) -> NSCollectionLayoutSection {
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0))
let layoutItem = NSCollectionLayoutItem(layoutSize: itemSize)
var layoutGroupSize = NSCollectionLayoutSize(widthDimension: .absolute(0), heightDimension: .absolute(0))
var layoutGroup = NSCollectionLayoutGroup.horizontal(layoutSize: layoutGroupSize, subitems: [layoutItem])
switch UIDevice.current.userInterfaceIdiom {
case .phone:
let a:CGFloat = UIScreen.main.bounds.size.height/8
let b:CGFloat = UIScreen.main.bounds.size.height
layoutGroupSize = NSCollectionLayoutSize(widthDimension: .absolute(b - (a) ), heightDimension: .absolute(b))
layoutGroup = NSCollectionLayoutGroup.horizontal(layoutSize: layoutGroupSize, subitems: [layoutItem])
layoutGroup.contentInsets = NSDirectionalEdgeInsets(top: a, leading: a/2, bottom: a, trailing: a/2)
case .pad:
let a:CGFloat = UIScreen.main.bounds.size.height*0.25
let h:CGFloat = a * 1.8
let b:CGFloat = UIScreen.main.bounds.size.height
layoutGroupSize = NSCollectionLayoutSize(widthDimension: .absolute(b - (h)), heightDimension: .absolute(b - (a)))
layoutGroup = NSCollectionLayoutGroup.horizontal(layoutSize: layoutGroupSize, subitems: [layoutItem])
layoutGroup.contentInsets = NSDirectionalEdgeInsets(top: a, leading: a/10, bottom: 0, trailing: a/10)
default:
print(UIScreen.main.bounds.size.height)
}
let layoutSection = NSCollectionLayoutSection(group: layoutGroup)
layoutSection.orthogonalScrollingBehavior = .groupPagingCentered
layoutSection.visibleItemsInvalidationHandler = { (items, offset, environment) in
items.forEach { item in
let distanceFromCenter = abs((item.frame.midX - offset.x) - environment.container.contentSize.width / 2.0)
let minScale: CGFloat = 0.7
let maxScale: CGFloat = 1.1
let scale = max(maxScale - (distanceFromCenter / environment.container.contentSize.width), minScale)
item.transform = CGAffineTransform(scaleX: scale, y: scale)
}
}
return layoutSection
}
Код: Выделить всё
class CarouselCell: UICollectionViewCell, SelfConfiguringCell {
static let reuseIdentifier: String = "carouselCell"
let title = UILabel()
let subtitle = UILabel()
let bookView = UIView()
let infoView = UIView()
let imageView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
title.font = UIFont.preferredFont(forTextStyle: .title2)
title.textColor = .label
subtitle.font = UIFont.preferredFont(forTextStyle: .title2)
subtitle.textColor = .secondaryLabel
let stackView = UIStackView(arrangedSubviews: [infoView])
stackView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(stackView)
infoView.backgroundColor = .blue
imageView.layer.cornerRadius = 5
imageView.clipsToBounds = true
imageView.contentMode = .scaleToFill
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
stackView.topAnchor.constraint(equalTo: contentView.topAnchor),
stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
}
func configure(with item: Item) {
}
required init?(coder: NSCoder) {
fatalError("Not happening")
}
}

Попробую объяснить. Например, у меня iPhone в горизонтальном положении с шириной экрана 932 пикселя. И у меня есть фоновое изображение шириной 1864 пикселей. У меня также есть определенное количество клеток. Я хочу разделить ширину фонового изображения (например, 1864 пикселей) на количество ячеек (например, 10), и когда пользователь прокручивает ячейки, я хочу, чтобы фоновое изображение перемещалось на +186,4 пикселей. вправо или влево в зависимости от направления движения.
А как сделать прокручиваемый фон?
Подробнее здесь: https://stackoverflow.com/questions/784 ... flowlayout
Мобильная версия