{"id":415,"date":"2016-03-03T00:43:21","date_gmt":"2016-03-03T00:43:21","guid":{"rendered":"http:\/\/strawberrycode.com\/blog\/?p=415"},"modified":"2021-05-07T17:21:38","modified_gmt":"2021-05-07T15:21:38","slug":"how-to-create-a-section-background-in-a-uicollectionview-in-ios-swift","status":"publish","type":"post","link":"https:\/\/strawberrycode.com\/blog\/how-to-create-a-section-background-in-a-uicollectionview-in-ios-swift\/","title":{"rendered":"How to create a Section Background in a UICollectionView in Swift"},"content":{"rendered":"<p>I recently faced a small challenge on a <code>UICollectionView<\/code>, the following screenshot illustrates pretty well the situation. In short: I needed to have a transparent background in a <code>UICollectionView<\/code> to be able to see through some sections, but I didn&#8217;t want to be able to see the background in between the cells on some others.<\/p>\n<figure style=\"width: 330px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" class=\"aligncenter\" src=\"https:\/\/raw.githubusercontent.com\/strawberrycode\/SCSectionBackground\/master\/Images\/SCSectionBackground_Example.png\" alt=\"Background colors per section on UICollectionView\" width=\"330\" height=\"600\" \/><figcaption class=\"wp-caption-text\">Background colors per section on UICollectionView<\/figcaption><\/figure>\n<p>Basically, I needed to be able to set different background colors per section. Well, needless to say that functionality doesn&#8217;t exist by default on iOS.<\/p>\n<p>Luckily for me I found this great article: <a href=\"http:\/\/www.ericjchapman.com\/ios-changing-the-section-background-color-in-a-uicollectionview.html\" target=\"_blank\" rel=\"noopener\">Changing the section background color in a UICollectionView<\/a> from Eric Chapman who did an amazing job cutting down the layout fuss to reveal the bare minimum. As the project I&#8217;m working on is written in Swift, I transcribed and adapted it and wanted to share it with you.<\/p>\n<p>Get ready to be amazed, you&#8217;re going to learn how to create a section background on <code>UICollectionView<\/code> and add color to it!<\/p>\n<p>Note: for those not used to the <code>CollectionViewFlowLayouts<\/code>, don&#8217;t worry, I have a comprehensive article (2 articles actually) nearly ready to be published, sit tight!<\/p>\n<h2>The magic<\/h2>\n<p>The idea is to override <code>UICollectionViewLayoutAttributes<\/code> to add a color attribute. And then override <code>UICollectionReusableView<\/code> apply the color to the view background. Easy peasy :)<\/p>\n<pre class=\"lang:swift decode:true \" title=\"SCSBCollectionViewLayoutAttributes\">class SCSBCollectionViewLayoutAttributes : UICollectionViewLayoutAttributes {\n \n    var color: UIColor = UIColor.whiteColor()\n    \n    override func copyWithZone(zone: NSZone) -&gt; AnyObject {\n        let newAttributes: SCSBCollectionViewLayoutAttributes = super.copyWithZone(zone) as! SCSBCollectionViewLayoutAttributes\n        newAttributes.color = self.color.copyWithZone(zone) as! UIColor\n        return newAttributes\n    }\n}\n\nclass SCSBCollectionReusableView : UICollectionReusableView {\n    override func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes) {\n        super.applyLayoutAttributes(layoutAttributes)\n        let scLayoutAttributes = layoutAttributes as! SCSBCollectionViewLayoutAttributes\n        self.backgroundColor = scLayoutAttributes.color\n    }\n}<\/pre>\n<h2>How to use it?<\/h2>\n<p>The idea is to loop over the cells in the selected section and add a background to that cell (or row, or section&#8230; your choice) and apply the color to it. In my implementation, you can even change the color by <code>indexPath<\/code>. How flexible! All this happens in the <code>UICollectionViewFlowLayout<\/code> used on your <code>UIcollectionView<\/code>.<\/p>\n<p>Here is an example of <code>layoutAttributesForElementsInRect<\/code>:<\/p>\n<pre class=\"lang:swift decode:true \" title=\"layoutAttributesForElementsInRect\">override func layoutAttributesForElementsInRect(rect: CGRect) -&gt; [UICollectionViewLayoutAttributes]? {\n\n    let attributes = super.layoutAttributesForElementsInRect(rect)\n    var allAttributes = [UICollectionViewLayoutAttributes]()\n    if let attributes = attributes {\n        for attr in attributes {\n\n            \/\/ Look for the first item in a row\n            \/\/ You can also calculate it by item (remove the second check in the if below and change the tmpWidth and frame origin\n\n            if (attr.representedElementCategory == UICollectionElementCategory.Cell &amp;amp;&amp;amp; attr.frame.origin.x == self.sectionInset.left) {\n                \/\/ Create decoration attributes\n                let decorationAttributes = SCSBCollectionViewLayoutAttributes(forDecorationViewOfKind: \"sectionBackground\", withIndexPath: attr.indexPath)\n\n                \/\/ Set the color(s)\n                if (attr.indexPath.section % 2 == 0) {\n                    decorationAttributes.color = UIColor.greenColor().colorWithAlphaComponent(0.5)\n                } else {\n                    decorationAttributes.color = UIColor.blueColor().colorWithAlphaComponent(0.5)\n                }\n            \n                \/\/ Make the decoration view span the entire row - or whatever you want ;)\n                let tmpWidth = self.collectionView!.contentSize.width\n                let tmpHeight = self.itemSize.height + self.minimumLineSpacing + self.sectionInset.top \/ 2 + self.sectionInset.bottom \/ 2 \/\/ or attributes.frame.size.height instead of itemSize.height if dynamic or recalculated\n                decorationAttributes.frame = CGRectMake(0, attr.frame.origin.y - self.sectionInset.top, tmpWidth, tmpHeight)\n                \/\/ Set the zIndex to be behind the item\n                decorationAttributes.zIndex = attr.zIndex - 1\n                \/\/ Add the attribute to the list\n                allAttributes.append(decorationAttributes)\n            }\n        }\n\n        \/\/ Combine the items and decorations arrays\n        allAttributes.appendContentsOf(attributes)\n    }\n    return allAttributes\n}<\/pre>\n<p>In my <a href=\"https:\/\/github.com\/strawberrycode\/SCSectionBackground\" target=\"_blank\" rel=\"noopener\">example on GitHub<\/a>, I used a <code>UICollectionView<\/code> with 4 sections, 3 cells with green background on the even sections and 7 cells on a blue background on the odd ones. Once the magic applied, I got something like that:<\/p>\n<figure style=\"width: 330px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" class=\"aligncenter\" src=\"https:\/\/raw.githubusercontent.com\/strawberrycode\/SCSectionBackground\/master\/Images\/SCSectionBackground.png\" alt=\"Background colors per section on UICollectionView\" width=\"330\" height=\"600\" \/><figcaption class=\"wp-caption-text\">Background colors per section on UICollectionView<\/figcaption><\/figure>\n<p>You can find the full code on GitHub: <a href=\"https:\/\/github.com\/strawberrycode\/SCSectionBackground\" target=\"_blank\" rel=\"noopener\">SCSectionBackground<\/a>.<\/p>\n<p>I hope that helps, and don&#8217;t hesitate to tweak, update, customize it ;)<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I recently faced a small challenge on a UICollectionView, the following screenshot illustrates pretty well the situation. In short: I needed to have a transparent background in a UICollectionView to be able to see through some sections, but I didn&#8217;t want to be able to see the background in between the cells on some others. Basically, I needed to be able to set different background colors per section. Well, needless to say that functionality doesn&#8217;t exist by default on iOS. Luckily for me I found this great article: Changing the section background color in a UICollectionView from Eric Chapman who &hellip; <a href=\"https:\/\/strawberrycode.com\/blog\/how-to-create-a-section-background-in-a-uicollectionview-in-ios-swift\/\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">How to create a Section Background in a UICollectionView in Swift<\/span> <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":431,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0},"categories":[40],"tags":[83,17,82,84,41,69,85],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v16.1.1 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to create a Section Background in a UICollectionView in Swift - StrawberryCode<\/title>\n<meta name=\"description\" content=\"I recently faced a small challenge on a UICollectionView: being able to change the background color per section, in Swift.\" \/>\n<link rel=\"canonical\" href=\"http:\/\/strawberrycode.com\/blog\/how-to-create-a-section-background-in-a-uicollectionview-in-ios-swift\/\" \/>\n<meta property=\"og:locale\" content=\"en_GB\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to create a Section Background in a UICollectionView in Swift - StrawberryCode\" \/>\n<meta property=\"og:description\" content=\"I recently faced a small challenge on a UICollectionView: being able to change the background color per section, in Swift.\" \/>\n<meta property=\"og:url\" content=\"http:\/\/strawberrycode.com\/blog\/how-to-create-a-section-background-in-a-uicollectionview-in-ios-swift\/\" \/>\n<meta property=\"og:site_name\" content=\"StrawberryCode\" \/>\n<meta property=\"article:published_time\" content=\"2016-03-03T00:43:21+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-05-07T15:21:38+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/strawberrycode.com\/blog\/wp-content\/uploads\/2016\/03\/SCSectionBackground.png\" \/>\n\t<meta property=\"og:image:width\" content=\"375\" \/>\n\t<meta property=\"og:image:height\" content=\"346\" \/>\n<meta name=\"twitter:label1\" content=\"Estimated reading time\">\n\t<meta name=\"twitter:data1\" content=\"3 minutes\">\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/strawberrycode.com\/blog\/#website\",\"url\":\"https:\/\/strawberrycode.com\/blog\/\",\"name\":\"StrawberryCode\",\"description\":\"Fruit for Thought\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":\"https:\/\/strawberrycode.com\/blog\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-GB\"},{\"@type\":\"ImageObject\",\"@id\":\"http:\/\/strawberrycode.com\/blog\/how-to-create-a-section-background-in-a-uicollectionview-in-ios-swift\/#primaryimage\",\"inLanguage\":\"en-GB\",\"url\":\"https:\/\/strawberrycode.com\/blog\/wp-content\/uploads\/2016\/03\/SCSectionBackground.png\",\"contentUrl\":\"https:\/\/strawberrycode.com\/blog\/wp-content\/uploads\/2016\/03\/SCSectionBackground.png\",\"width\":375,\"height\":346,\"caption\":\"How to create a Section Background on a UICollectionView -SCSectionBackground\"},{\"@type\":\"WebPage\",\"@id\":\"http:\/\/strawberrycode.com\/blog\/how-to-create-a-section-background-in-a-uicollectionview-in-ios-swift\/#webpage\",\"url\":\"http:\/\/strawberrycode.com\/blog\/how-to-create-a-section-background-in-a-uicollectionview-in-ios-swift\/\",\"name\":\"How to create a Section Background in a UICollectionView in Swift - StrawberryCode\",\"isPartOf\":{\"@id\":\"https:\/\/strawberrycode.com\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"http:\/\/strawberrycode.com\/blog\/how-to-create-a-section-background-in-a-uicollectionview-in-ios-swift\/#primaryimage\"},\"datePublished\":\"2016-03-03T00:43:21+00:00\",\"dateModified\":\"2021-05-07T15:21:38+00:00\",\"author\":{\"@id\":\"https:\/\/strawberrycode.com\/blog\/#\/schema\/person\/c328d959959928f47281d7a0ec779e2a\"},\"description\":\"I recently faced a small challenge on a UICollectionView: being able to change the background color per section, in Swift.\",\"breadcrumb\":{\"@id\":\"http:\/\/strawberrycode.com\/blog\/how-to-create-a-section-background-in-a-uicollectionview-in-ios-swift\/#breadcrumb\"},\"inLanguage\":\"en-GB\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"http:\/\/strawberrycode.com\/blog\/how-to-create-a-section-background-in-a-uicollectionview-in-ios-swift\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"http:\/\/strawberrycode.com\/blog\/how-to-create-a-section-background-in-a-uicollectionview-in-ios-swift\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"item\":{\"@type\":\"WebPage\",\"@id\":\"https:\/\/strawberrycode.com\/blog\/\",\"url\":\"https:\/\/strawberrycode.com\/blog\/\",\"name\":\"Home\"}},{\"@type\":\"ListItem\",\"position\":2,\"item\":{\"@type\":\"WebPage\",\"@id\":\"http:\/\/strawberrycode.com\/blog\/how-to-create-a-section-background-in-a-uicollectionview-in-ios-swift\/\",\"url\":\"http:\/\/strawberrycode.com\/blog\/how-to-create-a-section-background-in-a-uicollectionview-in-ios-swift\/\",\"name\":\"How to create a Section Background in a UICollectionView in Swift\"}}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/strawberrycode.com\/blog\/#\/schema\/person\/c328d959959928f47281d7a0ec779e2a\",\"name\":\"StrawberryCode\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","_links":{"self":[{"href":"https:\/\/strawberrycode.com\/blog\/wp-json\/wp\/v2\/posts\/415"}],"collection":[{"href":"https:\/\/strawberrycode.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/strawberrycode.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/strawberrycode.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/strawberrycode.com\/blog\/wp-json\/wp\/v2\/comments?post=415"}],"version-history":[{"count":18,"href":"https:\/\/strawberrycode.com\/blog\/wp-json\/wp\/v2\/posts\/415\/revisions"}],"predecessor-version":[{"id":587,"href":"https:\/\/strawberrycode.com\/blog\/wp-json\/wp\/v2\/posts\/415\/revisions\/587"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/strawberrycode.com\/blog\/wp-json\/wp\/v2\/media\/431"}],"wp:attachment":[{"href":"https:\/\/strawberrycode.com\/blog\/wp-json\/wp\/v2\/media?parent=415"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/strawberrycode.com\/blog\/wp-json\/wp\/v2\/categories?post=415"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/strawberrycode.com\/blog\/wp-json\/wp\/v2\/tags?post=415"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}