Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Configure cell at user defined index path

Hey there! Let’s say I got a collection view with some sections and some cells in each section. Now I want the user to be able to choose a cell by entering an index path in form of two integers in a text field. Then the user chooses a background color for the cell at the defined index path. How would you do that? Thanks a lot!

1 Answer

Assuming the integers can be equated to the collection view cells (for example if you're trying to access section 1 of a collection view that only has 1 section, you'll return nil and crash) you can set up a function that takes in parameters like this:

func chooseIndexPath(inSection: Int, forItem: Int, backgroundColor: UIColor) {
    let indexPath = NSIndexPath(forItem: forItem, inSection: inSection)
    let cell = collectionView.cellForItemAtIndexPath(indexPath)
    cell?.backgroundColor = backgroundColor
    collectionView.reloadData()
}

If you wanted them to choose a background color for it after they pick you can return the index path and pass that to a new function to be called at another time. The best way to do this though is for them not to input integers at all and just call the function in the didSelect delegate method of the collection view. Then you can have something like a popover controller pop up and create a protocol back that will pass the chosen color back to the main VC and reload the collection view.