如何在Swift中向TableView添加自定义单元格?

时间:2022-10-30 14:44:54

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!

我对iOS编程非常陌生,目前我正在尝试在导航条中使用add按钮向表视图添加新行。表中的每个单元格是一个带有UITextfield的自定义单元格。当我在模拟器中运行我的程序时,我的第一个单元格出现了,但是当我尝试添加另一个单元格时,tableView会变成一个黑屏(但是导航栏仍然停留在屏幕上)。请帮助!

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 个解决方案

#1


2  

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;
}

#2


0  

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行。让它成为一个变量,并在每次调用insertNewObject时增加它。

#1


2  

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;
}

#2


0  

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行。让它成为一个变量,并在每次调用insertNewObject时增加它。