Подтвердить что ты не робот

Как сделать верхний и нижний колонтитулы в виде коллекции быстрыми

Как сделать оба заголовка и нижнего колонтитула в виде коллекции в swift?

Я пытаюсь объединить заголовок и нижний колонтитул вместе, но он продолжает сбой, я не мог найти быстрый учебник, чтобы понять его.

Я не могу вернуть дополнительный вид для обоих, а всего лишь один.

Я установил их как на раскадровку (class + identifier) ​​

 override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    //#warning Incomplete method implementation -- Return the number of sections
    return 2
}


override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    //#warning Incomplete method implementation -- Return the number of items in the section
    return 10
}




override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
    var header: headerCell!
    var footer: footerCell!



    if kind == UICollectionElementKindSectionHeader {
        header =
            collectionView.dequeueReusableSupplementaryViewOfKind(kind,
                withReuseIdentifier: "header", forIndexPath: indexPath)
            as? headerCell

}
    return header

}

Ошибка:UICollectionElementKindCell с идентификатором один - должен зарегистрировать nib или класс для идентификатора или подключить прототип ячейки в раскадровке

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> profileCC {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("one", forIndexPath: indexPath) as! profileCC

    // Configure the cell

    return cell
}



override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

    switch kind {

    case UICollectionElementKindSectionHeader:

        let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "header", forIndexPath: indexPath) as! headerCell

        headerView.backgroundColor = UIColor.blueColor();
        return headerView

    case UICollectionElementKindSectionFooter:
        let footerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "footer", forIndexPath: indexPath) as! footerCell

        footerView.backgroundColor = UIColor.greenColor();
        return footerView

    default:

        assert(false, "Unexpected element kind")
    }
}

Я надеюсь, что кто-то поможет.

4b9b3361

Ответ 1

Вы можете сделать UICollectionViewController для обработки UICollectionView и в Interface Builder активировать разделы UICollectionView колонтитула и заголовка, тогда вы можете использовать следующий метод для предварительного просмотра в UICollectionView: добавлены два раздела:

override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

    switch kind {

    case UICollectionView.elementKindSectionHeader:

        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath)

        headerView.backgroundColor = UIColor.blue
        return headerView

    case UICollectionView.elementKindSectionFooter:
        let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Footer", for: indexPath)

        footerView.backgroundColor = UIColor.green
        return footerView

    default:

        assert(false, "Unexpected element kind")
    }

В приведенном выше коде я помещаю identifier нижнего колонтитула и заголовка, например, в Header и Footer, вы можете сделать это, как хотите. Если вы хотите создать пользовательский верхний или нижний колонтитул, вам необходимо создать подкласс UICollectionReusableView для каждого и настроить его по UICollectionReusableView.

Вы можете зарегистрировать свои пользовательские классы нижнего колонтитула и заголовка в Interface Builder или в коде следующим образом:

registerClass(myFooterViewClass, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "myFooterView")

Ответ 2

Обновлено для Свифта 3+

Шаг 1:

В своем классе контроллера представления зарегистрируйте класс, который будет использоваться в качестве верхнего или нижнего колонтитула, или обоих:

let collectionViewHeaderFooterReuseIdentifier = "MyHeaderFooterClass"

Шаг 2:

Если используется XIB, используйте:

collectionView.register(UINib(nibName: collectionViewHeaderFooterReuseIdentifier bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier:collectionViewHeaderFooterReuseIdentifier)

collectionView.register(UINib(nibName: collectionViewHeaderFooterReuseIdentifier bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier:collectionViewHeaderFooterReuseIdentifier)

Если не используется XIB:

collectionView.register(MyHeaderFooterClass.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: collectionViewHeaderFooterReuseIdentifier)

collectionView.register(MyHeaderFooterClass.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: collectionViewHeaderFooterReuseIdentifier)

Шаг 3:

Создайте собственный класс верхнего/нижнего колонтитула, реализация выглядит так:

import UIKit

class MyHeaderFooterClass: UICollectionReusableView {

 override init(frame: CGRect) {
    super.init(frame: frame)
    self.backgroundColor = UIColor.purple

    // Customize here

 }

 required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

 }
}

Шаг 4: Если не используется XIB, игнорируйте

  • Создайте новый пустой xib: "Файл → Новый файл → Пусто".

  • Назовите его точно таким же именем, как класс. В этом примере: "MyHeaderFooterClass"

  • Добавьте коллекцию многоразового просмотра в XIB.
  • Нажмите на этот объект, выберите Identity Inspector и измените класс этого объекта на "MyHeaderFooterClass".

Шаг 5: - Поддержите эту новую ячейку в представлении вашей коллекции с помощью метода делегата:

 func collectionView(_ collectionView: UICollectionView,
                    viewForSupplementaryElementOfKind kind: String,
                    at indexPath: IndexPath) -> UICollectionReusableView {

    switch kind {

    case UICollectionElementKindSectionHeader:
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: collectionViewHeaderFooterReuseIdentifier, for: indexPath)

        headerView.backgroundColor = UIColor.blue
        return headerView

    case UICollectionElementKindSectionFooter:
        let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: collectionViewHeaderFooterReuseIdentifier, for: indexPath)

        footerView.backgroundColor = UIColor.green
        return footerView

    default:
        assert(false, "Unexpected element kind")
    }
}

Шаг 6: Обработайте размер/сделайте так, чтобы он появился:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: 180.0)
}
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width: 60.0, height: 30.0)
}

Ответ 3

Чтобы дополнить оставшиеся ответы, не забудьте выделить пространство для ваших заголовков /collectionView:viewForSupplementaryElementOfKind:atIndexPath колонтитулов, иначе collectionView:viewForSupplementaryElementOfKind:atIndexPath не будет вызываться.

Сделайте это, выполнив collectionView:layout:referenceSizeForHeaderInSection в вашем источнике данных коллекции collectionView.

Ответ 4

После использования кода @mobilecat вы должны использовать эту функцию, чтобы появился верхний и нижний колонтитулы

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: 180.0)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width: 60.0, height: 30.0)
    }

Ответ 5

Решение

class CustomFlowLayout: UICollectionViewFlowLayout {

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let attributesForElementsInRect = super.layoutAttributesForElements(in: rect)
        var newAttributesForElementsInRect = [UICollectionViewLayoutAttributes]()

        for attributes in attributesForElementsInRect! {

            if !(attributes.representedElementKind == UICollectionElementKindSectionHeader
                || attributes.representedElementKind == UICollectionElementKindSectionFooter) {

                // cells will be customise here, but Header and Footer will have layout without changes.
            }

            newAttributesForElementsInRect.append(attributes)
        }

        return newAttributesForElementsInRect
    }
}


class YourViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let headerNib = UINib.init(nibName: "HeaderCell", bundle: nil)
        collectionView.register(headerNib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderCell")

        let footerNib = UINib.init(nibName: "FooterCell", bundle: nil)
        collectionView.register(footerNib, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "FooterCell")
    }


    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        switch kind {
        case UICollectionElementKindSectionHeader:
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderCell", for: indexPath) as! HeaderCell
            return headerView
        case UICollectionElementKindSectionFooter:
            let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "FooterCell", for: indexPath) as! FooterCell
            return footerView
        default:
            return UICollectionReusableView()
        }
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: 45)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: 25)
    }
}

Ответ 6

Обратите внимание, что ваш viewController должен реализовывать UICollectionViewDelegateFlowLayout, иначе эти методы не будут вызваны

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {

}

Ответ 7

В дополнение ко всем ответам выше

Чтобы активировать разделы нижнего колонтитула и верхнего колонтитула

Выберите свою коллекцию, затем выберите "Инспектор атрибутов" и проверьте разделы "Нижний колонтитул" и "Верхний колонтитул"

как на фото

enter image description here