Сначала создайте новый файл для контроллера представления коллекции. Этот файл должен быть подклассом UICollectionViewController
.
swiftCopy code class MyCollectionViewController: UICollectionViewController { let reuseIdentifier = "cell" override func viewDidLoad() { super.viewDidLoad() // Register cell classes self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) // Set background color self.collectionView?.backgroundColor = UIColor.white } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { // Return the number of sections return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // Return the number of items in the section return 10 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // Configure the cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) cell.backgroundColor = UIColor.blue return cell } }
Этот код устанавливает представление коллекции с одним разделом и десятью ячейками. Цвет фона ячейки установлен на синий.
Теперь вам нужно создать собственный макет для представления коллекции. Вы можете сделать это, создав подкласс UICollectionViewFlowLayout
.
swiftCopy code class MyFlowLayout: UICollectionViewFlowLayout { let itemSpacing: CGFloat = 10.0 override init() { super.init() self.minimumLineSpacing = itemSpacing self.minimumInteritemSpacing = itemSpacing self.sectionInset = UIEdgeInsets(top: itemSpacing, left: itemSpacing, bottom: itemSpacing, right: itemSpacing) self.itemSize = CGSize(width: 100.0, height: 100.0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
Этот код устанавливает простой макет с минимальным расстоянием между элементами и фиксированным размером для каждого элемента.
Наконец, вам нужно настроить представление коллекции с вашим пользовательским макетом и источником данных.
swiftCopy code class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let layout = MyFlowLayout() let collectionView = MyCollectionViewController(collectionViewLayout: layout) self.addChild(collectionView) self.view.addSubview(collectionView.view) collectionView.didMove(toParent: self) collectionView.view.translatesAutoresizingMaskIntoConstraints = false collectionView.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true collectionView.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true collectionView.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true collectionView.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true } }
Этот код устанавливает контроллер представления, который содержит представление коллекции.