当前位置: 首页 > news >正文

UIkit中使用新版UICollectionViewCompositionalLayout进行复杂布局(二)

文章目录

  • 一、前言
  • 二、示例代码

一、前言

此前使用UICollectionViewCompositionalLayout进行了简单使用,下面对此进行复杂布局使用,效果如下
在这里插入图片描述

二、示例代码


import UIKit
// MARK: - 数据模型
struct Product { let name: String }
struct Banner { let title: String }
struct User { let username: String }// 新增模型,用于示例
struct SpecialItem { let title: String }// MARK: - Section 类型
enum SectionType {case products([Product])case banners([Banner])case users([User])case mixedGroupsSection  // 同一 Section 中不同 Groupcase mixedItemsSection   // 同一 Group 中不同 Item
}class SucViewController: UIViewController {var sections: [SectionType] = [.products([Product(name: "🍎"), Product(name: "🍌"), Product(name: "🍓"), Product(name: "🍇")]),.banners([Banner(title: "限时优惠"), Banner(title: "新品上市")]),.users([User(username: "Alice"), User(username: "Bob"), User(username: "Charlie")]),.mixedGroupsSection,.mixedItemsSection]private lazy var collectionView: UICollectionView = {let layout = createLayout()let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)cv.backgroundColor = .systemBackgroundcv.dataSource = selfcv.delegate = selfcv.register(ProductCell.self, forCellWithReuseIdentifier: "ProductCell")cv.register(BannerCell.self, forCellWithReuseIdentifier: "BannerCell")cv.register(UserCell.self, forCellWithReuseIdentifier: "UserCell")cv.register(SpecialCell.self, forCellWithReuseIdentifier: "SpecialCell")cv.translatesAutoresizingMaskIntoConstraints = falsereturn cv}()override func viewDidLoad() {super.viewDidLoad()view.addSubview(collectionView)NSLayoutConstraint.activate([collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)])}// MARK: - Compositional Layoutfunc createLayout() -> UICollectionViewCompositionalLayout {return UICollectionViewCompositionalLayout { [weak self] sectionIndex, _ -> NSCollectionLayoutSection? inguard let self = self else { return nil }let sectionType = self.sections[sectionIndex]switch sectionType {case .products:let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.5), heightDimension: .absolute(100)))item.contentInsets = NSDirectionalEdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 5)let group = NSCollectionLayoutGroup.horizontal(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(100)),subitems: [item, item])return NSCollectionLayoutSection(group: group)case .banners:let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.8), heightDimension: .absolute(120)))item.contentInsets = NSDirectionalEdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 5)let group = NSCollectionLayoutGroup.horizontal(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.8), heightDimension: .absolute(120)),subitems: [item])let section = NSCollectionLayoutSection(group: group)section.orthogonalScrollingBehavior = .continuousreturn sectioncase .users:let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(60)))item.contentInsets = NSDirectionalEdgeInsets(top: 5, leading: 10, bottom: 5, trailing: 10)let group = NSCollectionLayoutGroup.horizontal(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(60)),subitems: [item])return NSCollectionLayoutSection(group: group)case .mixedGroupsSection:// 同一 Section 内不同 Grouplet item1 = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(80)))item1.contentInsets = NSDirectionalEdgeInsets(top: 5, leading: 10, bottom: 5, trailing: 10)let item2 = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(120)))item2.contentInsets = NSDirectionalEdgeInsets(top: 5, leading: 10, bottom: 5, trailing: 10)let group1 = NSCollectionLayoutGroup.horizontal(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(80)),subitems: [item1])let group2 = NSCollectionLayoutGroup.horizontal(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(120)),subitems: [item2])let mixGroup = NSCollectionLayoutGroup.vertical(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(200)),subitems: [group1, group2])let section = NSCollectionLayoutSection(group: mixGroup)return sectioncase .mixedItemsSection:// 同一 Group 内不同 Item(高度不同)let item1 = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.5), heightDimension: .absolute(80)))item1.contentInsets = NSDirectionalEdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 5)let item2 = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.5), heightDimension: .absolute(120)))item2.contentInsets = NSDirectionalEdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 5)let group = NSCollectionLayoutGroup.horizontal(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(120)),subitems: [item1, item2])return NSCollectionLayoutSection(group: group)}}}
}// MARK: - 数据源
extension SucViewController: UICollectionViewDataSource {func numberOfSections(in collectionView: UICollectionView) -> Int { sections.count }func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {switch sections[section] {case .products(let items): return items.countcase .banners(let items): return items.countcase .users(let items): return items.countcase .mixedGroupsSection: return 2 // group 数量case .mixedItemsSection: return 2  // item 数量}}func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {switch sections[indexPath.section] {case .products(let items):let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProductCell", for: indexPath) as! ProductCellcell.configure(with: items[indexPath.item].name)return cellcase .banners(let items):let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BannerCell", for: indexPath) as! BannerCellcell.configure(with: items[indexPath.item].title)return cellcase .users(let items):let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UserCell", for: indexPath) as! UserCellcell.configure(with: items[indexPath.item].username)return cellcase .mixedGroupsSection:let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SpecialCell", for: indexPath) as! SpecialCellcell.configure(with: "Group \(indexPath.item+1)")return cellcase .mixedItemsSection:let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SpecialCell", for: indexPath) as! SpecialCellcell.configure(with: "Item \(indexPath.item+1)")return cell}}
}// MARK: - Delegate
extension SucViewController: UICollectionViewDelegate { }// MARK: - 新增 Cell
class SpecialCell: UICollectionViewCell {private let label = UILabel()override init(frame: CGRect) {super.init(frame: frame)contentView.backgroundColor = .systemPurplecontentView.layer.cornerRadius = 12contentView.clipsToBounds = truelabel.translatesAutoresizingMaskIntoConstraints = falselabel.textAlignment = .centerlabel.font = .boldSystemFont(ofSize: 18)label.textColor = .whitecontentView.addSubview(label)NSLayoutConstraint.activate([label.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),label.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)])}required init?(coder: NSCoder) { fatalError() }func configure(with text: String) { label.text = text }
}// MARK: - Cell
class ProductCell: UICollectionViewCell {private let label = UILabel()override init(frame: CGRect) {super.init(frame: frame)contentView.backgroundColor = .systemBluecontentView.layer.cornerRadius = 12contentView.clipsToBounds = truelabel.translatesAutoresizingMaskIntoConstraints = falselabel.textAlignment = .centerlabel.font = .boldSystemFont(ofSize: 20)contentView.addSubview(label)NSLayoutConstraint.activate([label.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),label.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)])}required init?(coder: NSCoder) { fatalError() }func configure(with text: String) { label.text = text }
}class BannerCell: UICollectionViewCell {private let label = UILabel()override init(frame: CGRect) {super.init(frame: frame)contentView.backgroundColor = .systemOrangecontentView.layer.cornerRadius = 12contentView.clipsToBounds = truelabel.translatesAutoresizingMaskIntoConstraints = falselabel.textAlignment = .centerlabel.font = .boldSystemFont(ofSize: 18)contentView.addSubview(label)NSLayoutConstraint.activate([label.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),label.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)])}required init?(coder: NSCoder) { fatalError() }func configure(with text: String) { label.text = text }
}class UserCell: UICollectionViewCell {private let label = UILabel()override init(frame: CGRect) {super.init(frame: frame)contentView.backgroundColor = .systemGreencontentView.layer.cornerRadius = 12contentView.clipsToBounds = truelabel.translatesAutoresizingMaskIntoConstraints = falselabel.textAlignment = .centerlabel.font = .boldSystemFont(ofSize: 18)contentView.addSubview(label)NSLayoutConstraint.activate([label.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),label.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)])}required init?(coder: NSCoder) { fatalError() }func configure(with text: String) { label.text = text }
}
http://www.dtcms.com/a/464755.html

相关文章:

  • 网站建设的技术问题苏州吴江建设局招标网站
  • 河南省村镇建设处网站网站配色与布局 教材
  • Prometheus运维之路(ES监控接入)
  • OpenAMP专题(一):一文了解OpenAMP全貌
  • C++ 中 rfind 方法详解
  • SpringBoot 教程(十四) SpringBoot之集成 Redis(优化版)
  • 【Linux】线程同步与互斥(上)
  • 图观 模型编辑器
  • Win11 输入延迟与鼠标卡顿:系统化排查与优化指南
  • 【开题答辩全过程】以 爱运动健身小程序的设计与实现为例,包含答辩的问题和答案
  • Linux 内核IIO sensor驱动
  • 《Linux系统编程之入门基础》【Linux的前世今生】
  • 活动汪活动策划网站龙岗建设网站
  • Apache IoTDB 架构特性与 Prometheus+Grafana 监控体系部署实践
  • LLM时代基于unstructured解析非结构化pdf
  • uniapp tab切换及tab锚点效果(wx小程序及H5端)
  • Hadoop面试题及详细答案 110题 (71-85)-- 集群部署与运维
  • 5-1〔OSCP ◈ 研记〕❘ SQL注入攻击▸SQL注入理论基础
  • 南充市企业网站建设wordpress极客主题
  • 企业做小红书关键词搜索排名推广时,怎么找到小红书上有一定搜索量但竞争度低的蓝海词?
  • 数据仓库与数据挖掘基础知识
  • 鸿蒙:使用Rating组件实现五角星打分评价
  • 外国人可以在中国做网站吗做个网站得花多少钱
  • 双均线策略
  • 【vLLM 学习】Neuron
  • 网站做行业认证好处施工企业在施工过程中发现工程设计图纸存在差错的
  • 迅为RK3576开发板挂载Windows以及虚拟机Ubuntu测试
  • 第1篇:创建基础电商AI客服
  • 【MyBatis从入门到入土】告别JDBC原始时代:零基础MyBatis极速上手指南
  • MaxScript 科研绘图教程:从数据到精确的可视化