带有原型单元格的tableView.insertRowsAtIndexPaths

时间:2015-10-03 03:42:07

标签: xcode swift tableview

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

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您可以使用cellForRowAtIndexPath并在函数内部,您可以使用deque原型单元格。这是一个例子

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
}

答案 1 :(得分:0)

我刚刚完成它,我的错误是我不知道每次插入或添加新单元格时都会调用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
}