简体   繁体   中英

Swift - Create a UITableViewController with one static cell at the top and the rest be dynamic cells?

I am having trouble making a table view with one static cell at the very top of my table view. This table view will hold 4 buttons and the rest of the views will hold a list of the user's songs.

I have already looked into other answers on here but all of them seem to be written in Objective C not swift.

    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

    }

This is what I have been using to just set the regular table views. How would I go about modifying this code to allow for a static cell at the top and dynamic cells for the rest?​

Don't use Static Cells . Choose Dynamic Prototypes in your table view and create 2 prototype cells.

在此处输入图片说明

And return first cell in first section, other cells in second section

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
    }
}

You can use the HeaderView of the table for that, just give your custom view to the . tableHeaderView property Example:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM