自定义 header 的 table 视图与 IB
Custom header of table view with IB
我想使用界面生成器为 table 视图部分创建自定义 header。我不能使用 titleForHeaderInSection 方法,因为我需要显示两个标签。我使用了这个说明:Customizing Header and Footer of TableView in iOS8 但它不起作用。
到目前为止我做了什么:
- 创建自定义 class CustomTableCell 继承自 UITableViewCell
class CustomTableCell: UITableViewCell {
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var dateDescriptionLabel: UILabel!
}
- 在故事板中创建动态原型单元
- 添加标识符
- 将标签连接到自定义 UITableViewCell
- 实施
viewForHeaderInSection
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCellWithIdentifier("CustomTableCell") as CustomTableCell
headerCell.backgroundColor = UIColor.cyanColor()
headerCell.dateLabel.text = "Test date"
headerCell.dateDescriptionLabel.text = "Test date description"
return headerCell
}
当我 运行 应用程序时,该部分出现一秒钟,然后移动到 table 单元格下方,我收到错误消息:table 没有索引路径正在重复使用的单元格.
这个解决方案有什么问题?我从链接的教程中下载了该项目,它在那里工作。
您的问题根源在于 UIKit 如何处理 UITableView。
为了确保 table 视图快速且响应迅速,即使有大量单元格,单元格也会被重新使用。
通过调用 tableView.dequeueReusableCellWithIdentifier("CustomTableCell")
,您要求 tableView 为您提供一个单元格以供重复使用。
很多人一直在使用可重复使用的单元格在 Storyboards 中设计他们的 headers/footers。自从 iOS 7 Beta 5 以来,这可能会导致错误。这个答案很好地解释了这种情况:What is the meaning of the “no index path for table cell being reused” message in iOS 6/7?
要设计您自己的自定义 header/footer 视图,我不建议使用 UITableViewCells。相反,您应该直接在代码中创建和设计自定义 UIView。如果您想使用 Interface Builder,您可以创建一个 .xib 或在您的 Storyboard 中创建一个视图,该视图不是实际控制器视图的子视图。
我想使用界面生成器为 table 视图部分创建自定义 header。我不能使用 titleForHeaderInSection 方法,因为我需要显示两个标签。我使用了这个说明:Customizing Header and Footer of TableView in iOS8 但它不起作用。
到目前为止我做了什么:
- 创建自定义 class CustomTableCell 继承自 UITableViewCell
class CustomTableCell: UITableViewCell {
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var dateDescriptionLabel: UILabel!
}
- 在故事板中创建动态原型单元
- 添加标识符
- 将标签连接到自定义 UITableViewCell
- 实施
viewForHeaderInSection
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCellWithIdentifier("CustomTableCell") as CustomTableCell
headerCell.backgroundColor = UIColor.cyanColor()
headerCell.dateLabel.text = "Test date"
headerCell.dateDescriptionLabel.text = "Test date description"
return headerCell
}
当我 运行 应用程序时,该部分出现一秒钟,然后移动到 table 单元格下方,我收到错误消息:table 没有索引路径正在重复使用的单元格.
这个解决方案有什么问题?我从链接的教程中下载了该项目,它在那里工作。
您的问题根源在于 UIKit 如何处理 UITableView。 为了确保 table 视图快速且响应迅速,即使有大量单元格,单元格也会被重新使用。
通过调用 tableView.dequeueReusableCellWithIdentifier("CustomTableCell")
,您要求 tableView 为您提供一个单元格以供重复使用。
很多人一直在使用可重复使用的单元格在 Storyboards 中设计他们的 headers/footers。自从 iOS 7 Beta 5 以来,这可能会导致错误。这个答案很好地解释了这种情况:What is the meaning of the “no index path for table cell being reused” message in iOS 6/7?
要设计您自己的自定义 header/footer 视图,我不建议使用 UITableViewCells。相反,您应该直接在代码中创建和设计自定义 UIView。如果您想使用 Interface Builder,您可以创建一个 .xib 或在您的 Storyboard 中创建一个视图,该视图不是实际控制器视图的子视图。