Мне нужно создать представление в проекте Swift с двумя разделами разграничения. Первый имеет семь ячеек с квадратной формой. Второй имеет три ячейки с прямоугольной формой. Данные внутри ячеек являются статическими. Во всех случаях разделы должны соответствовать всей ширине экрана (в основном в ландшафтном режиме).Разделы с разным размером ячейки с UICollectionView
У меня нет большого опыта работы с использованием UICollectionViewController
, поэтому я решил сделать это, используя один UICollectionViewController
класс и две многоразовые клетки, но когда я установил первую ширину секции ячейки второй также влияет, а затем клетки ширины разрезается.
Является ли мой вопрос правильным? Должен ли я использовать разные UICollectionViewController
(по одному разделу)?
Update: Моего код контроллера
import UIKit
class InverterController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let moduleCell = "moduleCell"
let parameterCell = "parameterCell"
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if section > 0 {
return CGSizeZero
} else {
return CGSize(width: collectionView.frame.width, height: CGFloat(195))
}
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtPath indexPath: NSIndexPath) -> CGSize {
var newSize = CGSizeZero
if indexPath.section == 0 {
newSize = CGSizeMake(CGFloat(105), CGFloat(105))
} else {
newSize = CGSizeMake(CGFloat(313), CGFloat(200))
}
return newSize
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "inverterHeader", forIndexPath: indexPath)
return headerView
default:
assert(false, "Unexpected element kind")
}
}
/**
Two sections in this UICollectionView: First one for clock items, second one for other parameters.
*/
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 2
}
/**
First section contains one cell
Second section contains three cells
*/
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
var items = 0
if section == 0 {
items = 7
} else {
items = 3
}
return items
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cellIdentifier = ""
if indexPath.section == 0 {
cellIdentifier = moduleCell
} else {
cellIdentifier = parameterCell
}
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath)
cell.layer.cornerRadius = 6
cell.layer.masksToBounds = true
return cell
}
}
конфигурация
Interface Builder для CollectionView
Simulator скриншота (не желаемый результат, все клетки имеют одинаковую ширину)
Привет Сэм, я изменил код в этом методе, но результат тот же. Я добавил свой код и изображения, если вы можете проверить его и получить лучшую идею. Спасибо – Spacemonkey
@ Julián Это потому, что одно из ваших имен параметров неверно. В этой строке 'func collectionView (collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtPath indexPath: NSIndexPath) -> CGSize {' Заменить 'sizeForItemAtPath' с' sizeForItemAtIndexPath' или вы можете просто скопировать эту строку из моего ответа, чтобы быть уверенным. –
Ок Сэм, который помог мне прояснить проблему. Но сейчас у меня есть другие сомнения, чтобы спросить в разных вопросах SO. Я принимаю ваш ответ. спасибо – Spacemonkey