Swift-如何选择哪些单元格进入哪个部分(UITableView)?

时间:2015-07-23 21:14:28

标签: ios swift uitableview

我已经做到了:

var data = ["Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry",
    "Clementine", "Coconut", "Cranberry", "Fig", "Grape", "Grapefruit",
    "Kiwi fruit", "Lemon", "Lime", "Lychee", "Mandarine", "Mango",
    "Melon", "Nectarine", "Olive", "Orange", "Papaya", "Peach",
    "Pear", "Pineapple", "Raspberry", "Strawberry"]
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"]

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 12
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return data.count
}


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

    // Configure the cell...

    cell.textLabel?.text = data[indexPath.row]

    return cell
}

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return months[section]
}

现在我如何选择数据数组中的哪些变量进入哪个“月”部分?有没有我应该使用的方法,我不知道? (这是一个扩展UITableView的类)

1 个答案:

答案 0 :(得分:2)

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> InttableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell有section和indexPath参数,indexPath有section变量。所以基本上你应该在这些函数中做一些switch语句来根据月份返回所需的数据。每个月拥有一组数据可能是个更好的主意。或者是多维数组,甚至是一些自定义数据类型。 无论如何,代码可能是这样的:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        return dataJanuary.count
    }
    else if section == 1 {
        return dataFebruary.count
    }
    // ...
    return 0
}

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

    // Configure the cell...
    if indexPath.section == 0 {
        cell.textLabel?.text = dataJanuary[indexPath.row]
    }
    else if indexPath.section == 1 {
        cell.textLabel?.text = dataFebruary[indexPath.row]
    }
    // ...
    return cell
}