在我的UITableView中返回两个不同的部分

时间:2015-02-13 17:26:21

标签: ios uitableview swift

我试图在我的UITableView中返回两个单独的.counts。我有点知道它背后的逻辑,但没有正确使用语法。我怎样才能做到这一点?我想要它做的是用两个.counts填充我的tableview。我还想在第一部分和第二部分的顶部放置一个标签。什么都有帮助! 这是我迄今为止所拥有的,但我只获得了第一部分细胞。为什么它不显示.counts?

func tableView(tableView: UITableView, numberOfSectionsInTableView: Int) -> Int{
        return 2;
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if (section == 0){
           return featSubNames.count
        }
        else{
            return subCatNames.count
        }

    }
    func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {
        if (section == 0){
            ????
        }
        if (section == 1){
            ????
        }
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell

        // Configure the cell
        switch (indexPath.section) {

        case 0:
            cell.textLabel?.text = featSubName[indexPath.row]
            cell.textLabel?.textColor = UIColor.whiteColor()
        case 1:
            cell.textLabel?.text = subCatNames[indexPath.row]
            cell.textLabel?.textColor = UIColor.whiteColor()
        default:
            cell.textLabel?.text = "Other"

        }



        return cell
    }

1 个答案:

答案 0 :(得分:1)

您的代码似乎是正确的。要在每个部分的标题上获取UIViews,您可以返回从UIView继承的任何对象(这并不意味着它会很好)。因此,如果你想要这个,你可以返回一个带有UIImageView和UILabel的小容器。

viewHeader的代码是这样的:

func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {
    // instantiate the view to be returned and placed correctly
    let commonLabel = UILabel(frame: CGRectMake(0, 0, tableWidth, 30))
    commonLabel.textColor = .blackColor()
    commonLabel.textAlignment = .Center
    // ... other settings in the properties

    if section == 0 {
        commonLabel.text = "section1"
        // other settings for the first section
    }
    if section == 1 {
        commonLabel.text = "section2"
        // other settings ...
    }
    return commonLabel
}

注意:

请务必设置容器视图的框架,对于sectionHeaders,层次结构中的顶视图不接受自动布局。

实现viewForHeaderInSection方法对于自定义UI更易于访问,如果您愿意,可以使用TitleForHeaderInSection,但它仅限于更复杂的内容。

编辑:

如果您正在使用故事板,您仍然可以使用此代码,尽管就使用IB用于UI的应用而言,它并不那么优雅。为此,您可以查看以下链接:How to Implement Custom Table View Section Headers and Footers with Storyboard 。这仅使用故事板实现视图,但必须编写委托部分。