iOS Swift - UICollectionView - Sections different background color - ios

Is there a way to set different background colors to UICollectionView's header and the content view?
I want my collection's header background color - clearColor and the content background to be white.
Thank you!

You can change the UICollectionViewCell background color within cellForItemAtIndexPath and the section header background within viewForSupplementaryElementOfKind
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.backgroundColor = UIColor.magentaColor()
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
cell.backgroundColor = UIColor.whiteColor()
return cell
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 10
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "header", forIndexPath: indexPath)
if kind == UICollectionElementKindSectionHeader {
headerView.backgroundColor = UIColor.clearColor()
}
return headerView
}

Related

UICollectionViewCell not updating view after selection

Have an issue where:
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
is called when an item is selected, but I cannot change any cell properties from this method.
I created a new project with a stripped down UICollectionViewController to change the background color of a cell when selected. It also doesn't work. Here it is:
import UIKit
private let reuseIdentifier = "Cell"
class CollectionViewController: UICollectionViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
cell.backgroundColor = UIColor.blue
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = self.collectionView(self.collectionView, cellForItemAt: indexPath)
cell.backgroundColor = UIColor.green
}
}
The only thing I did in Storyboard is delete the standard View Controller and replace it with a UICollectionViewController, create a subclass of UICollectionViewController and set the controller in the storyboard as that class.
Also, I can confirm that the cell's index path is returned from this method when called from inside the didSelectItemAt method:
self.collectionView.indexPathsForSelectedItems
You are using the wrong API. Never call the delegate method collectionView(_ cellForItemAt:, use cellForItem(at:
if let cell = collectionView.cellForItem(at: indexPath) {
cell.backgroundColor = UIColor.green
}
But be aware that this change is not persistent. When the user scrolls the color will change back to blue.
You can achieve that as below,
ViewController
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ColoursViewCell", for: indexPath) as! ColoursViewCell
return cell
}
UICollectionViewCell
class ColoursViewCell: UICollectionViewCell {
#IBOutlet var photoImageView: UIImageView?
override var bounds: CGRect {
didSet {
self.layoutIfNeeded()
}
}
override var isSelected: Bool{
didSet{
if self.isSelected{
self.photoImageView?.backgroundColor = UIColor.random
}else{
self.photoImageView?.backgroundColor = UIColor.lightGray
}
}
}
}
you can have sample projects from this link I have in GitHub
https://github.com/hadanischal/RandomColors/tree/develop

Put UICollectionViewCell into UICollectionView

I am using LBTAComponents pod
this is a pod that makes easier to work with UICollectionView
without any need to register anything and provides a super simple anchoring system ... and in the first project I've got two days ago I decided to use this framework
but now I have a problem in one of uicollectionviewCells I need another collectionview that I can fill with items then I need it to be scrollable horizontally
import LBTAComponents
import UIKit
class ProductCell: DatasourceCell {
let cellId = "cellid"
let collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = .black
return cv
}()
override func setupViews() {
super.setupViews()
ProductCell.addSubview(collectionView)
collectionView.frame = frame
collectionView.register(UICollectionView.self, forCellWithReuseIdentifier: cellId)
collectionView.dataSource = self
}
}
extension ProductCell : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
cell.backgroundColor = .white
return cell
}
}
datasourceCell is equal to UICollectionViewCell in this pod.
and now I am getting this ERROR :
instance member 'addsubview' cannot be used on type uiview did you use the value of this type instead?
could you please help me?
I tried to use self.addSubview(collectionView)
but I got another error enter image description here
You can simply use a UITableView with custom UITableViewCells containing a UICollectionView.
Example:
1. View Hierarchy
2. UIViewController containing UITableView
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
return tableView.dequeueReusableCell(withIdentifier: "tcell", for: indexPath) as! TableCell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
if indexPath.row == 0
{
return 120
}
else
{
return 150
}
}
}
3. Custom UITableViewCell containing UICollectionView
class TableCell: UITableViewCell, UICollectionViewDataSource
{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
return collectionView.dequeueReusableCell(withReuseIdentifier: "ccell", for: indexPath)
}
}
4. Output Screenshot
addsubview is an instance method, not a class method. So you should use:
self.addSubview(collectionView)
instead of:
ProductCell.addSubview(collectionView)

UICollection View

I have a reusable collection view cell. I am trying to set an image at didselect at index path but when i select a cell it return more than cell returning same image.
Here is the code.
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return 1
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CollectionViewCell
cell.userImage.layer.cornerRadius = cell.userImage.frame.size.width/2
cell.userImage.clipsToBounds = true
return cell
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int{
return 10
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! CollectionViewCell
cell.userStatusImage.image = UIImage(named: "selectedcontact.png")
collectionView.reloadData()
}
You need to keep track of the selected cells.
var selectedIndexes = [Int]()
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
if self.selectedIndexes.contains(indexPath.row){
cell.backgroundColor = UIColor.redColor()
}
else{
cell.backgroundColor = UIColor.whiteColor()
}
return cell
}
// MARK: UICollectionViewDelegate
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if selectedIndexes.contains(indexPath.row){
selectedIndexes.removeObject(indexPath.row)
}
else{
selectedIndexes.append(indexPath.row)
}
collectionView.reloadData()
}
Swift array don't have method to removeObject. Here is an extension for that
extension Array {
mutating func removeObject<U: Equatable>(object: U) -> Bool {
for (idx, objectToCompare) in self.enumerate() {
if let to = objectToCompare as? U {
if object == to {
self.removeAtIndex(idx)
return true
}
}
}
return false
}
}
It seems the last line of code collectionView.reloadData() will reload all the cell to initial status since you don't have any place checking whether one specific cell is selected or not.

collectionView footer not showing

I've checked the section footer as shown in the screenshot below.
I've also implemented the dataSource method:
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionHeader {
var header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "Header", forIndexPath: indexPath) as? DetailHeader
if header == nil {
header = DetailHeader()
}
return header!
} else {
println("footer")
var footer = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "Footer", forIndexPath: indexPath) as! UICollectionReusableView
return footer
}
}
I was able to display my header, but my footer is never displayed. The println never triggers either.
Screen shot from storyboard:
2.My code:
import UIKit
class BaseCVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cvcCell", forIndexPath: indexPath)
return cell;
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return Int(2)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return CGSizeMake(self.view.frame.size.width, 20)
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionHeader {
let header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "header", forIndexPath: indexPath)
return header
} else {
print("footer")
let footer = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "footer", forIndexPath: indexPath)
return footer
}
}
}
Result in simulator:
Important note: I've used Xcode 7 beta 5 (Swift 2.0)
Option 1: Set the footerReferenceSizeon your UICollectionViewDelegateFlowLayout greater than 0
Option 2: Implement the collectionView(_:layout:referenceSizeForFooterInSection:)
function in you UICollectionViewDelegateFlowLayout.
Drag and drop
CollectionReusableView
for both header and footer in
UICollectionViewController
from storyBoard and give identifier for each. The same process you drag and drop UITableViewCell in UITableView and give cell identifier.
Good luck

UICollectionView not working using swift without storyboard

I am trying to set up UICollectionView in my view controller. I am created custom cell CVCell.xib. My collection view is not showing up at all. What's missing in my code?
In my viewController.swift file:
#IBOutlet var collectionViewNew: UICollectionView?
override func viewDidLoad() {
super.viewDidLoad()
self.collectionViewNew?.registerNib(UINib(nibName: "CVCell", bundle: nil), forCellWithReuseIdentifier: "CVCell")
}
func numberOfSectionsInCollectionView(
collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return 6
}
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CVCell", forIndexPath: indexPath) as CVCell
cell.backgroundColor = UIColor.orangeColor()
return cell
}

Resources