Swift-创建一个UITableViewController,顶部有一个静态单元格,其余是动态单元格?

时间:2019-05-19 01:12:10

标签: ios swift xcode

我无法在表格视图的顶部使用一个静态单元格制作表格视图。此表格视图将包含4个按钮,其余视图将保留用户歌曲的列表。

我已经在这里研究了其他答案,但是所有答案似乎都是用目标C编写的。

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sortedSongs.count
    }

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

        //cell.songTitle.text = albumList[indexPath.row]
        //cell.songArtist.text = artistList[indexPath.row]
        //cell.songImage.image = imageList[indexPath.row]

        return cell

    }

这就是我用来设置常规表格视图的方法。我将如何修改此代码以在顶部保留一个静态单元格而在其余部分保留一个动态单元格呢?

2 个答案:

答案 0 :(得分:1)

请勿使用Static Cells。在表格视图中选择Dynamic Prototypes,然后创建2个原型单元格。

enter image description here

并在第一部分返回第一个单元格,在第二部分返回其他单元格

override func numberOfSections(in tableView: UITableView) -> Int {
    return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        return 1
    } else if section == 1 {
        return sortedSongs.count
    } else if section == 2 {
        return anotherArrayCount  
    }
    return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "FirstCell", for: indexPath) as! FirstCell
        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "RecentCell", for: indexPath) as! RecentCell
        //cell.songTitle.text = albumList[indexPath.row]
        //cell.songArtist.text = artistList[indexPath.row]
        //cell.songImage.image = imageList[indexPath.row]
        return cell
    }
}

答案 1 :(得分:-1)

您可以为此使用表的HeaderView,只需将自定义视图提供给即可。 tableHeaderView属性 示例:

override func viewDidLoad() {
   super.viewDidLoad()
   let myCustomView = MyCustomView()
   tableView.tableHeaderView = myCustomView
}

文档:https://developer.apple.com/documentation/uikit/uitableview/1614904-tableheaderview

相关问题