UICollectionView с двумя заголовками
Имеете два заголовка в UICollectionView?
У меня есть UICollectionView, который использует макет потока, который также имеет верхний и нижний колонтитул:
---------
| head |
---------
| A | B |
---------
| C | D |
---------
| foot |
---------
Иногда я хотел бы иметь два заголовка, например:
---------
| head1 |
---------
| head2 |
---------
| A | B |
---------
| C | D |
---------
| foot |
---------
Я зациклился на том, как добиться этого. Кажется, что только макет потока имеет одну голову и одну ногу. Как добавить второй заголовок?
edit: Я также реализовал липкие заголовки - http://blog.radi.ws/post/32905838158/sticky-headers-for-uicollectionview-using - но я хочу, чтобы первый заголовок был липким. Вот почему я не могу просто включить все в один заголовок.
Ответы
Ответ 1
Вам просто нужно использовать простой трюк. Настроить заголовок и нижний колонтитул как для всех разделов.
В каком разделе вы не хотите показывать нижний колонтитул, просто передайте его нулевой размер как: -
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
if(section==0)
{
return CGSizeZero;
}
return CGSizeMake(320, 50);
}
Здесь я использовал два раздела, например
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 2;
}
И не передал строки из только одной секции, которая является последней, как
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
if (section==1) {
return 20;
}
return 0;
}
И вот мой вывод ---
![enter image description here]()
Красный вид - это заголовок, а зеленый - нижний колонтитул.
Здесь вы можете получить весь файл реализации
Ответ 2
Этот контент может помочь вам достичь желаемого
создайте класс CollectionHeaderView
и сделайте его вывод из UICollectionReusableView
и создайте контейнер, а затем после make 2 uiview и поместите его в этот контейнер
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
UICollectionReusableView *reusableview = nil;
if (kind == UICollectionElementKindSectionHeader) {
CollectionHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
headerView.firstContainer.titleLabel.text = @"MY Header View 1";//Here you can set title
headerView.secondContainer.titleLabel.text = @"MY Header View 2";//Here you can set title
UIImage *headerImage = [UIImage imageNamed:@"header_banner.png"];
headerView.firstContainer.backgroundImage.image = headerImage;
headerView.secondContainer.backgroundImage.image = headerImage;
reusableview = headerView;
}
if (kind == UICollectionElementKindSectionFooter) {
UICollectionReusableView *footerview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterView" forIndexPath:indexPath];
reusableview = footerview;
}
return reusableview;
}
Ответ 3
Вы должны поместить оба заголовка (1 и 2) в другое представление и поместить это представление в виде главы 1. Таким образом, создайте только заголовок в представлении коллекции.
Ответ 4
Как вы добавляете один заголовок? Я полагаю, указав заголовки разделов? Рецепт, чтобы иметь два заголовка, состоял бы в том, чтобы иметь два заголовка заголовка внутри основного представления заголовка.
Ответ 5
Что вы можете сделать, это использовать UITableView с двумя разделами и поместить UICollectionView в ячейку второго раздела.
Ответ 6
Получив эту работу, создав два вида в заголовке многократного использования, реализуйте липкий заголовок, только если секция является второй секцией. Кроме того, я корректирую числоOfSection до 2. Получил переключение заголовков, скрыв и показывая представления в viewForSupplementaryElementOfKind.
Ответ 7
Определите свой UICollectionViewCell, который будет вашим видом заголовка вида UICollectionElementKindSectionHeader. В моем случае у меня есть два заголовка: OfferHeaderCell и APRHeaderCell, как указано ниже:
verticalCollectionView.register(UINib(nibName: "OfferHeaderCell", bundle: nil), forSupplementaryViewOfKind:UICollectionElementKindSectionHeader, withReuseIdentifier: "OfferHeaderCell")
verticalCollectionView.register(UINib(nibName: "APRHeaderCell", bundle: nil), forSupplementaryViewOfKind:UICollectionElementKindSectionHeader, withReuseIdentifier: "APRHeaderCell")
Идем дальше и возвращаем заголовок для каждого раздела, а затем устанавливаем размер заголовка раздела, чтобы иметь нулевой размер в этой функции UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if(section==0) {
return CGSize.zero
} else if (section==1) {
return CGSize(width:collectionView.frame.size.width, height:133)
} else {
return CGSize(width:collectionView.frame.size.width, height:100)
}
}
Важно определить viewForSupplementaryElementOfKind для двух разных разделов, как показано ниже:
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
var reusableview = UICollectionReusableView()
if (kind == UICollectionElementKindSectionHeader) {
let section = indexPath.section
switch (section) {
case 1:
let firstheader: OfferHeaderCell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "OfferHeaderCell", for: indexPath) as! OfferHeaderCell
reusableview = firstheader
case 2:
let secondHeader: APRHeaderCell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "APRHeaderCell", for: indexPath) as! APRHeaderCell
reusableview = secondHeader
default:
return reusableview
}
}
return reusableview
}
И, наконец, Datasource,
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if (section==2) {
return 2
}
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = verticalCollectionView.dequeueReusableCell(withReuseIdentifier: "ReviseOfferCell", for: indexPath)
cell.backgroundColor = UIColor.white
return cell
}
Примечание. Не забудьте добавить UICollectionFlowLayout, как показано ниже:
//MARK: UICollectionViewDelegateFlowLayout
extension MakeAnOfferController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.item == 0 {
return CGSize(width: self.view.frame.size.width, height: 626.0)
}
return CGSize()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if(section==0) {
return CGSize.zero
} else if (section==1) {
return CGSize(width:collectionView.frame.size.width, height:133)
} else {
return CGSize(width:collectionView.frame.size.width, height:100)
}
}
}