Edit uitableviewcell text on tap in iOS swift

 

This tutorial has been updated for X code 7.3 & swift 2.2

Its so much easier to edit list on the fly instead of opening another screen & editing uitableviewcell text. I don’t know why there is no method for it. Apple wants us to create segue & keep moving around different screens. The solution is little long and complicated but here it goes.

  1. First lets set up the x code project as usual. Create new single view application X code project. Set project name to edit text on tap & save it on desktop.

new x code project

 

2. Go to main storyboard & select view controller & delete it. Add tableview controller in main storyboard.

add table view controller

 

3. Select tableview controller & make it initial view controller

set initial view controller

 

 

4. Now delete view controller swift file & add new cocoa touch class file of class UITableViewController

add table view controller swift file

 

5. Go to main storyboard; select table view controller & set its class to TableViewController

set custom class

 

6. Create new cocoa touch class file of class NSObject & name it ListItem

add nsobject swift file

 

7. Create string property called text & initialize it

import UIKit

class ListItem: NSObject {
var text: String

init(text: String) {
    self.text = text
}

}

8. Create new cocoa touch class file of class UITableViewCell

table view cell swift file

 

9. Go to TableViewController swift file & create array to hold table data

var listItems = [ListItem]()

10. Add following code in view did load

    // 1
    tableView.registerClass(TableViewCell.self, forCellReuseIdentifier: "tableCell")

    // 2
    listItems += [ListItem(text: "towel"), ListItem(text: "sheets"), ListItem(text: "soap"), ListItem(text: "shampoo"), ListItem(text: "brush"), ListItem(text: "bucket"), ListItem(text: "shower"), ListItem(text: "curtains"), ListItem(text: "door"), ListItem(text: "window")]
  1. Set cell class to TableViewCell & cell identifier to tableCell
  2. Add 10 items to the array

11. Set number of sections to 1 & number of rows to listItems.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 listItems.count
}

12. Open TableViewCell swift file & add required init method. This way if variables are not initialized then it shows this error.

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

13. Add textfield delegate to class TableViewCell

class TableViewCell: UITableViewCell, UITextFieldDelegate {

14. Create label as textfield & variable listItems as instance of class ListItem

let label:UITextField

var listItems:ListItem? {
    didSet {
        label.text = listItems!.text
    }
}

15. Add override init method & add following code

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    // 1
    label = UITextField(frame: CGRect.null)
    label.textColor = UIColor.blackColor()
    label.font = UIFont.systemFontOfSize(16)

    super.init(style: style, reuseIdentifier: reuseIdentifier)
    // 2
    label.delegate = self
    label.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
    // 3
    addSubview(label)

}
  1. Entire cell is set as textfield. Labels color & font is set.
  2. Label textfield delegate is TableViewCell. Label is aligned center in cell. If you omit this list then label will be at top part of each cell.
  3. Label is added as subview

16. Add label in layout subviews & add some left margin for label

let leftMarginForLabel: CGFloat = 15.0

override func layoutSubviews() {
    super.layoutSubviews()
    label.frame = CGRect(x: leftMarginForLabel, y: 0, width: bounds.size.width - leftMarginForLabel, height: bounds.size.height)
}

17. When return key is pressed on keyboard then keyboard will disappear

func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return false
}

18. When editing is done then textfields text is added to the array

func textFieldShouldEndEditing(textField: UITextField) -> Bool {
        if listItems != nil {
            listItems?.text = textField.text
        }
        return true
    }

19. Go to TableViewController swift file & uncomment cell for row at index path method & add following code

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath) as! TableViewCell

    // Configure the cell...
    let item = listItems[indexPath.row]
    cell.listItems = item
    cell.selectionStyle = UITableViewCellSelectionStyle.None

    return cell
}

Now build and run app in iPhone 5s & edit any row of table by just touching on it.

edit cell text
Download X code file
Problem is when keyboard hides table rows behind it.
Challenge: Move editing row to top of tableview & reduce opacity of non editing row

edit cell text with moving cells
Download Challenge Solution

Total 8 Votes
3

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?