首页 > 解决方案 > 如何在表格视图中为每一行添加标题

问题描述

我正在构建一个 iOS 应用程序,其中包含表视图中的集合视图。我有三行,每行都有一个集合视图。我计划为每一行的每个部分设置三个部分。例如行,一个应该在带有标题的单独部分中,对于第 2 行和第 3 行也是如此。每当我创建三个部分时,我都会在所有三个部分中获得所有三行。我想有一个单独的部分,每行都有一个标题。

import UIKit

class StoreVC: UIViewController,UITableViewDelegate,UITableViewDataSource {


    @IBOutlet weak var CourseTableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        CourseTableView.tableFooterView = UIView()
        
        CourseTableView.delegate = self
        CourseTableView.dataSource = self
    }
    
   func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 0
        {
            return "Courses"
        }
        
        else if section == 1
        {
            return "Tests"
        }
        
        return "Bundles"
    }
    
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return 1
    }
    

    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       
        
        if indexPath.row == 0
        {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CourseRow
            
            return cell
        }
        
        else if indexPath.row == 1
        {
            let cell = tableView.dequeueReusableCell(withIdentifier: "testcell", for: indexPath) as! TestRow
            
            return cell
        }
        
        else if indexPath.row == 2
        
        {
            let cell = tableView.dequeueReusableCell(withIdentifier: "bundlecell", for: indexPath) as! BundleRow
            
            return cell
        }
        
        return UITableViewCell()
        
        
        
    }
    
    
    


}

标签: iosswiftuitableviewuicollectionviewuitableviewsectionheader

解决方案


在您的 Xcode-playground 上尝试此代码并根据需要进行自定义。导入 UIKit 导入 PlaygroundSupport

class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        3
    }

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

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UILabel()
        headerView.text = "Header: \(section)"
        return headerView
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = "Cell: \(indexPath)"
        return cell
    }
}

PlaygroundPage.current.liveView = ViewController()

推荐阅读