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

Как изменить цвет фона в целом разделе в UICollectionView?

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

Я не вижу каких-либо методов делегирования, никаких предложений?

4b9b3361

Ответ 1

Идея состоит в том, чтобы переопределить UICollectionViewLayoutAttributes, чтобы добавить атрибут цвета. Затем переопределите UICollectionReusableView, чтобы применить цвет к фону представления.

https://github.com/strawberrycode/SCSectionBackground

Ответ 2

Это отличный учебник по изменению цвета раздела UICollectionView:

Обновлена ​​ссылка, благодаря пользователю @casamia

http://www.ericjchapman.com/jekyll/update/ios/2014/11/10/ios-changing-section-background-color-in-UICollectionView.html

В принципе, нам придется подклассы UICollectionViewLayoutAttributes, UICollectionReusableView и UICollectionViewLayout, чтобы создать экземпляр UICollectionReusableView в виде фонового представления раздела.

Это его результат:

введите описание изображения здесь

Пожалуйста, перейдите по ссылке для получения более подробной информации.

Ответ 3

Я еще не пробовал это, но мне кажется, что вам нужно использовать декорации, если вам нужен фон за вашими ячейками (например, полка в приложении "Книги" ). Я думаю, что вы должны иметь разные представления для каждого раздела и настраивать их с помощью метода делегата layoutAttributesForDecorationViewOfKind:atIndexPath:.

Ответ 4

В представлении коллекции каждый раздел может иметь дополнительные виды, поэтому добавьте дополнительные виды для каждого раздела, а затем установите цвет фона для дополнительных представлений вместо секций секции. Надеюсь, это поможет.

Ответ 5

Это очень просто, просто используйте этот метод UICollectionViewDelegate по умолчанию, он будет работать

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    print(indexPath.item)

    let evenSectionColor = UIColor.clear
    let oddSectionColor = UIColor.white
    cell.contentView.backgroundColor = (indexPath.item % 2 == 0) ? evenSectionColor : oddSectionColor

}

Ответ 6

обратитесь к:
клубничный код: используйте Украшение как  фон
devxoul: используйте SupplementaryElement в качестве фона
airbnb: используйте SupplementaryElement в качестве фона

Мне нужно совместимо с IGListKit, поэтому я использую decorationView в качестве  фон. Макет является подклассом из UICollectionViewFlowLayout для общего случая использования. Моя реализация: different section background

Ответ 7

Я ушел из этого репо здесь https://github.com/SebastienMichoy/CollectionViewsDemo/tree/master/CollectionViewsDemo/Sources/Collections%20Views

Swift 3

подкласс uicollectionreusableview

class SectionView: UICollectionReusableView {
   static let kind = "sectionView"
}

подкласс uicollectionViewFlowLayout

class CustomFlowLayout: UICollectionViewFlowLayout {

// MARK: Properties

var decorationAttributes: [IndexPath: UICollectionViewLayoutAttributes]
var sectionsWidthOrHeight: [IndexPath: CGFloat]


// MARK: Initialization

override init() {
    self.decorationAttributes = [:]
    self.sectionsWidthOrHeight = [:]

    super.init()
}

required init?(coder aDecoder: NSCoder) {
    self.decorationAttributes = [:]
    self.sectionsWidthOrHeight = [:]

    super.init(coder: aDecoder)
}

// MARK: Providing Layout Attributes

override func layoutAttributesForDecorationView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
    return self.decorationAttributes[indexPath]
}

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    var attributes = super.layoutAttributesForElements(in: rect)
    let numberOfSections = self.collectionView!.numberOfSections
    var xOrYOffset = 0 as CGFloat

    for sectionNumber in 0 ..< numberOfSections {
        let indexPath = IndexPath(row: 0, section: sectionNumber)
        let numberOfItems = self.collectionView?.numberOfItems(inSection: sectionNumber)
        let sectionWidthOrHeight = numberOfItems == 0 ? UIScreen.main.bounds.height : collectionViewContentSize.height//self.sectionsWidthOrHeight[indexPath]!
        let decorationAttribute = UICollectionViewLayoutAttributes(forDecorationViewOfKind: SectionView.kind, with: indexPath)
        decorationAttribute.zIndex = -1

        if self.scrollDirection == .vertical {
            decorationAttribute.frame = CGRect(x: 0, y: xOrYOffset, width: self.collectionViewContentSize.width, height: sectionWidthOrHeight)
        } else {
            decorationAttribute.frame = CGRect(x: xOrYOffset, y: 0, width: sectionWidthOrHeight, height: self.collectionViewContentSize.height)
        }

        xOrYOffset += sectionWidthOrHeight

        attributes?.append(decorationAttribute)
        self.decorationAttributes[indexPath] = decorationAttribute
    }

    return attributes
}
}

реализовать это

Функция делегата CollectionView

func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {

    Log.printLog(identifier: elementKind, message: indexPath)
    if elementKind == UICollectionElementKindSectionHeader, let view = view as? ProfileViewHeaderView {

        view.backgroundColor = UIColor(red: (102 / 255.0), green: (169 / 255.0), blue: (251 / 255.0), alpha: 1)
    } else if elementKind == SectionView.kind {
        let evenSectionColor = UIColor.black
        let oddSectionColor = UIColor.red

        view.backgroundColor = (indexPath.section % 2 == 0) ? evenSectionColor : oddSectionColor
    }
}

Это важно

let layout = CustomFlowLayout()
layout.register(SectionView.self, forDecorationViewOfKind: SectionView.kind)

зарегистрируйте UICollectionReusableView с макетом, а не CollectionView.

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

Ответ 8

Я изменил цвет фона каждого раздела очень простым способом следующим образом: Но я не был уверен, правильно ли это делать. Но это сработало.

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    FamilyCalendarCellItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"calendarItem" forIndexPath:indexPath];
    Event *event;
    _headerView = [collectionView dequeueReusableSupplementaryViewOfKind:
                   UICollectionElementKindSectionHeader withReuseIdentifier:@"EventHeader" forIndexPath:indexPath]; //headerView is declared as property of Collection Reusable View class
    if(indexPath.section==0) {

        cell.backgroundColor=[UIColor orangeColor];
        }
    else if(indexPath.section==1) {

        cell.backgroundColor=[UIColor yellowColor];

    }

    return cell;
}