tableView.insertRowsAtIndexPaths 带有原型单元格

tableView.insertRowsAtIndexPaths with prototype cell

我正在尝试在我的 tableView 中插入一个原型单元格。我定义了两个原型单元并为它们提供了唯一标识符,但我无法使用特定标识符插入它们。 没有 tableView.insertRowsAtIndexPaths 带标识符的函数。

大家有什么想法吗?

您可以使用 cellForRowAtIndexPath 并在函数内部,您可以对原型单元格进行双端队列。这是一个例子

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //you can also have if condition here to choose between ur prototype cells
        let cell = tableView.dequeueReusableCellWithIdentifier("unique id_1", forIndexPath: indexPath) as! UITableViewCell 

        // Configure the cell...

        return cell
    }

这是更常见的方法

//In parent class
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "MainCatSelectedSegue" {
        if let tvc = segue.destinationViewController as? YourTableViewControllerClass{
            tvc.model = self.model //the data you wanna populate the table view with. If the model is not from this current class, you can ingore this
        }
    }
}

//In tableview calss
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if indexPath.row % 2 != 0{
        let cell = tableView.dequeueReusableCellWithIdentifier("SubIncomeCat", forIndexPath: indexPath) as! TableViewCell //or UITableViewCell if you have no custom calls for cells
    }
    let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.CellReusIdentifier, forIndexPath: indexPath) as! TableViewCell

    // Configure the cell...
    let rowContent = yourModel[indexPath.section][indexPath.row]
    //now fill the cell with the content like...
    //cell.textLabel?.text = rowContent.text
    //cell.detailTextLabel?.text = rowContent.detail

    return cell
}

我刚刚完成,我的错误是我不知道每次插入或添加新单元格时都会调用 cellForRowAtIndexPath。 我试图检查 shouldPerformSegueWithIdentifier 的条件并使用特定原型相应地插入一个单元格。下面是对我有用的代码。

override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool { 
if identifier == "MainCatSelectedSegue" { 
   let TableRow = (tableView.indexPathForSelectedRow?.row)! 
   let x = NSIndexPath(forItem: (Int(TableRow) + 1), inSection: 0)
   TableDataSource.insert(item, atIndex: Int(TableRow) + 1)
   tableView.insertRowsAtIndexPaths([x], withRowAnimation: .Automatic)  
} 
return false 
} 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell : UITableViewCell
    if TableDataSource[indexPath.row].Parent != "" {
        //This is a sub category
        cell = tableView.dequeueReusableCellWithIdentifier("SubIncomeCat", forIndexPath: indexPath)        
    }else{
    cell = tableView.dequeueReusableCellWithIdentifier("MainIncomeCat", forIndexPath: indexPath)
    }
        let Item = TableDataSource[indexPath.row] as TreeItem
    cell.textLabel?.text = Item.Name    
    return cell
}