Correct the spelling errors in a UITableView

 

Tap on a cell to scroll up a keyboard. Correct the spelling and then press the return key.

Source code in Correct.zip

  1. main.m
  2. Class CorrectAppDelegate
  3. Class TableViewController

tableView:didDeselectRowAtIndexPath:

When a cell is selected, the tableView:didDeselectRowAtIndexPath: method of the table view delegate is called. This method adds a UITextField to the cell, temporarily covering the cell’s textLabel. The position, content, and color (fore and background) of the UITextField exactly match those of the textLabel. When you press return, the UITextField’s text will be copied into the cell and the UITextField will be destroyed.

Minor details. A cell turns blue when it is selected. This makes it hard to see the vertical blue insertion point, so we call deselectRowAtIndexPath:animated: to fade the blue back to white.

A UILabel displays its text centered vertically. A UITextField displays its text upper-left justified. (Try to find this in the documentation!) That’s why we needed the variable dy.

We change the textLabel’s text to a blank just in case the background color is clear. I would have preferred to change the cell’s text to the null string @"", or to nil, but then the edited text never appeared in the cell after the user pressed return. Why?

The methods

Three methods of the data source provide the data:

  1. numberOfSectionsInTableView:
  2. tableView:numberOfRowsInSection:
  3. tableView:cellForRowAtIndexPath: returns a UITableViewCell