快速混合静态和动态细胞

时间:2017-10-13 14:58:15

标签: ios swift

我在tableView中有动态单元格,但在动态单元格的顶部,我想添加一个包含两个标签的静态单元格。 我搜索但我没有找到我的解决方案。 我该怎么办? (我是初学者)

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

        return dictionary.count
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : TicketDetailTableViewCell =  tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TicketDetailTableViewCell

        var dict = dictionary[indexPath.row]
        cell.lblComment.text = dict["comment"] as? String
        cell.lblDate.text = dict["date"] as? String

        return cell


    }

2 个答案:

答案 0 :(得分:0)

你有几个选择......

  1. 使用.tableHeaderView - 您可以使用任何正常的UIView +子视图,标签,图片等等

  2. 创建第二个原型单元格,并将该单元格用作"第一行"。你可以将它放在故事板中,但是你想要...只是因为它是一个原型单元格,并不代表你在使用它时必须改变任何东西。

  3. 方法2最终看起来与此类似:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        // if it's the first row, show the prototype cell with
        // identifier "StaticCell"
        if indexPath.row == 0 {
    
            let cell = tableView.dequeueReusableCell(withIdentifier: "StaticCell", for: indexPath)
            return cell
    
        }
    
        // it's not the first row, so show the prototype cell with
        // identifier "cell"
        //
        // Note: you will need to "offset" the array index since the
        // "2nd row" is indexPath.row == 1
        let cell : TicketDetailTableViewCell =  tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TicketDetailTableViewCell
    
        var dict = dictionary[indexPath.row - 1]
        cell.lblComment.text = dict["comment"] as? String
        cell.lblDate.text = dict["date"] as? String
    
        return cell
    }
    
    // you will also need to return +1 on the number of rows
    // so you can "add" the first, static row
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dictionary.count + 1
    }
    

答案 1 :(得分:-1)

主要思想是实现heightForRow数据源方法,根据单元索引路径,您将返回静态高度或自动高度。像这样:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.row == staticCellIndex {
        return 80.0
    }
    return UITableViewAutomaticDimension
}
相关问题