How do I add custom cells to TableView in Swift?

2.9k views Asked by At

I am very new to iOS programming and I am currently trying to use an add button in my navigation bar to add a new row to my table view. Each cell in the table is a custom cell with a UITextfield. When I run my program in the simulator my first cell shows up, but when I try to add another one the tableView becomes a black screen (but the navigation bar still stays on the screen). Please help!

import UIKit

class TrivialDecisionsController: UITableViewController
{

var objects = [listedDecision]()

override func awakeFromNib() {
    super.awakeFromNib()

}

override func viewDidLoad()
{

    super.viewDidLoad()
    self.navigationItem.leftBarButtonItem = self.editButtonItem()

    let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
    self.navigationItem.rightBarButtonItem = addButton
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func insertNewObject(sender: AnyObject?)
{
    let newDecision = tableView.dequeueReusableCellWithIdentifier("trivialDecision") as! listedDecision
    newDecision.configure(text: "", placeholder: "Decision Title")
    self.objects.insert(newDecision, atIndex:0)
    let indexPath = NSIndexPath(forRow: 0, inSection: 0)
    self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
    tableView.reloadData()   
}

// MARK: - Table View

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // 1
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return objects.count+1
}

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

    //cell.configure(text: "", placeholder: "Enter some text!")
    return cell
}

override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
           return true
}

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        objects.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {

        objects.append(listedDecision())

       array, and add a new row to the table view.
    }
}
}

Here is the code for my custom Cell as well

import UIKit

class listedDecision: UITableViewCell, UITextFieldDelegate {


@IBOutlet weak var decisionTitle: UITextField!
/*var ID: String
var cellstyle:UITableViewCellStyle*/


override func awakeFromNib() {
    super.awakeFromNib()


    // Initialization code
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

func configure(#text: String?, placeholder: String)
{
    decisionTitle.text = text
    decisionTitle.placeholder = placeholder
    decisionTitle.accessibilityValue = text
    decisionTitle.accessibilityLabel = placeholder
}


}
2

There are 2 answers

0
Himanshu gupta On

In your code, the lines:

 self.objects.insert(newDecision, atIndex:0)
 let indexPath = NSIndexPath(forRow: 0, inSection: 0)

take constant zero. So every time, when you click the button to add new cell, it adds to the row 0. So make it a variable and increment it on every call to insertNewObject.

0
Shanmugasundharam On

Use this code

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

var cell: MyCustomCell = tableView.dequeueReusableCellWithIdentifier("ThemeCell") as MyCustomCell

let theme = themes[indexPath.row]

cell.myLabel.text = theme.themeName
cell.myImageView.image = UIImage(named: "test.png")

println("The loaded image: \(cell.myImageView.image)")

return cell;
}