В UICollectionView я хочу, чтобы весь раздел был однородным цветом фона, а не для отдельной ячейки или для всего представления коллекции.
Я не вижу каких-либо методов делегирования, никаких предложений?
В UICollectionView я хочу, чтобы весь раздел был однородным цветом фона, а не для отдельной ячейки или для всего представления коллекции.
Я не вижу каких-либо методов делегирования, никаких предложений?
Идея состоит в том, чтобы переопределить UICollectionViewLayoutAttributes, чтобы добавить атрибут цвета. Затем переопределите UICollectionReusableView, чтобы применить цвет к фону представления.
Это отличный учебник по изменению цвета раздела UICollectionView:
В принципе, нам придется подклассы UICollectionViewLayoutAttributes
, UICollectionReusableView
и UICollectionViewLayout
, чтобы создать экземпляр UICollectionReusableView в виде фонового представления раздела.
Это его результат:
Пожалуйста, перейдите по ссылке для получения более подробной информации.
Я еще не пробовал это, но мне кажется, что вам нужно использовать декорации, если вам нужен фон за вашими ячейками (например, полка в приложении "Книги" ). Я думаю, что вы должны иметь разные представления для каждого раздела и настраивать их с помощью метода делегата layoutAttributesForDecorationViewOfKind:atIndexPath:
.
В представлении коллекции каждый раздел может иметь дополнительные виды, поэтому добавьте дополнительные виды для каждого раздела, а затем установите цвет фона для дополнительных представлений вместо секций секции. Надеюсь, это поможет.
Это очень просто, просто используйте этот метод 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
}
обратитесь к:
клубничный код: используйте Украшение как
фон
devxoul: используйте SupplementaryElement в качестве фона
airbnb: используйте SupplementaryElement в качестве фона
Мне нужно совместимо с IGListKit
, поэтому я использую decorationView
в качестве
фон. Макет является подклассом из UICollectionViewFlowLayout
для общего случая использования. Моя реализация:
Я ушел из этого репо здесь 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. вы должны изменить его для своего собственного проекта.
Я изменил цвет фона каждого раздела очень простым способом следующим образом: Но я не был уверен, правильно ли это делать. Но это сработало.
- (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;
}