Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.