将添加的行设置为第一个indexPath行

时间:2016-02-17 01:55:46

标签: ios xcode swift tableview uisegmentedcontrol

我有3个分段控制器视图,还有一个我在tableview中添加了一个额外的自定义单元格。我的问题是如何在其中一个案例中设置自定义单元格,以便在视图加载时始终设置在tableView的顶部?谢谢!

@available(iOS 2.0, *)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let myCell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath)

    switch(mySegmentedControl.selectedSegmentIndex)

    {



    case 0:
        myCell.textLabel!.text = globalList[indexPath.row]
        break

    case 1:
        myCell.textLabel!.text = friendsList[indexPath.row]
        break


    case 2:

    // *** I want to add a Cell here with a "Add Item" IBAction ---------------------

        if(indexPath.row == meList.count) {

            myCell.textLabel?.text = "+ Add Item"
            // add new row here
            /* OR add new button here as cell's subview  */
            // set frame of your button
            // set target and selector method of button
            // [cell addSubView: addButton]

        }
        else {

            myCell.textLabel?.text = meList[indexPath.row]
        }


    default:
        break


    }

    return myCell

}

1 个答案:

答案 0 :(得分:0)

首先,在tableView(_:numberOfRowsInSection:)中,您需要+ 1返回的数字,因此还有一行。 (仅在mySegmentedControl.selectedSegmentIndex == 2时执行此操作。)

然后在tableView(_:cellForRowAtIndexPath:)中,如果mySegmentedControl.selectedSegmentIndex == 2indexPath.row == 0(第一个单元格),请配置并返回“添加项目”单元格。

这一额外行的插入将使所有索引偏移1.因此,在else语句中,您需要myCell.textLabel?.text = meList[indexPath.row - 1]。这样,例如,当indexPath.row == 1时,您将返回数组的第一个元素(第0个索引)。

相关问题