How to customize uitableviewcell background color like clear app
This tutorial has been updated for X code 7.3 & swift 2.2
Whenever you create any kind of to do list you should always reorder according to priority. To make it explicit without label or button you could use contextual cues like changing background color. This way you could have less clutter in your app & still conveys the message.
- First lets set up the x code project as usual. Create new single view application X code project. Set project name to prioritize tablecell & save it on desktop.
2. Go to main storyboard & select view controller & delete it. Add tableview controller in main storyboard.
3. Select tableview controller & make it initial view controller
4. Now delete view controller swift file & add new cocoa touch class file of class uitableviewcontroller
5. Go to main storyboard; select table view controller & set its class to TableViewController
6. Select prototype cell & set its identifier to tableCell
7. Go to TableViewController swift file & create an array called tableData as follows
class TableViewController: UITableViewController { var tableData = ["one", "two", "three", "four", "six", "seven", "eight", "nine", "ten"]
8. Set number of sections to 1 & number of rows in section to tableData.count
override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return tableData.count }
9. Uncomment cellForRowAtIndexPath method & add following code
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath) // Configure the cell... cell.textLabel?.text = tableData[indexPath.row] return cell }
10. Add following code for changing uitableViewCells background color
func colorForIndex(index: Int) -> UIColor { let itemCount = tableData.count - 1 let color = (CGFloat(index) / CGFloat(itemCount)) * 0.6 return UIColor(red: 1.0, green: color, blue: 0.0, alpha: 1.0) } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { cell.backgroundColor = colorForIndex(indexPath.row) }
Now build and run app in iPhone 5s
Download X code file
Challenge 1: Remove cell separators & maintain cell background color when selected
Challenge 2: Create a gradient to show where cell ends & new cell starts.