ios - 如何在表格视图中为每一行添加标题
问题描述
我正在构建一个 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()
}
}
解决方案
在您的 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()
推荐阅读
- android - 防止 SQLite Android 中的重复数据
- heroku - Heroku 上的 Rails API GraphQL 服务器不工作
- python - Python/Pandas:使用来自三个列表之一的信息分配新列的值
- ios - 为什么UITableView回到前面时只显示一半的数据
- reactjs - 如何在将 textarea 的值放入我的复制缓冲区时使用“onCopy”更改 textarea 的值
- r - R中按日期范围的新变量
- html - 在定价表中放置一个“最受欢迎”的圆圈
- sql-server - SQL:使用逐行值过滤列
- sql - 在 SQL 中创建详尽的案例列
- python - Flask 应用程序为来自公共 IP 的路由提供 404