例如,这是我的自定义单元格:
protocol SectionHeaderTableViewCellDelegate {
func didSelectUserHeaderTableViewCell(sectionHeader: SectionHeaderTableViewCell, selected: Bool, type: Type)
}
class SectionHeaderTableViewCell: UITableViewCell {
@IBOutlet weak var labelContainerView: LabelContainerView!
@IBOutlet weak var sectionTitleLabel: UILabel!
@IBOutlet weak var plusButton: UIButton!
var type: Type?
var delegate: SectionHeaderTableViewCellDelegate?
var dog: Dog?
let sections = [Type.Meals, Type.Exercise, Type.Health, Type.Training, Type.Misc]
}
extension SectionHeaderTableViewCell {
@IBAction func plusButtonPressed(sender: AnyObject) {
if let type = type {
delegate?.didSelectUserHeaderTableViewCell(self, selected: plusButton.selected, type: type )
}
}
在我的 Controller 中,如果我添加 header.contenView 的返回,我会得到 header 保留在适当位置的所需结果,但不幸的是,它会使自定义 header 中包含的按钮无效,从而阻止其被调用。否则,如果我只是返回标题,自定义标题单元格上的按钮将按预期工作,但标题会随着被删除的行而移动,这显然不雅观,不是我想要的。
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let header = tableView.dequeueReusableCellWithIdentifier("sectionHeader") as? SectionHeaderTableViewCell else { return UITableViewCell() }
header.delegate = self
header.updateDogWithGender(dog)
header.type = header.sections[section]
header.sectionTitleLabel.text = header.sections[section].rawValue
return header.contentView
}
最佳答案
如果有人遇到类似的情况,解决方案是创建一个 Nib 文件并根据需要对其进行自定义。通过转到文件 -> 新文件 -> iOS -> 用户界面 -> 并选择查看来创建 nib 文件。 Create Nib file 。我添加了我的 View 和按钮以获得我想要的外观。 customize Nib 。从那里,我将自定义单元格类更改为 UITableViewHeaderFooterView,并将我的导出和操作重新连接到新的 Nib 文件。
class SectionHeaderView: UITableViewHeaderFooterView {... previous code from above }
返回 Controller 更新 viewForHeaderInSection 函数以加载 Nib :
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = NSBundle.mainBundle().loadNibNamed("SectionHeader", owner: self, options: nil).first as? SectionHeaderView
header?.delegate = self
header?.updateDogWithGender(dog)
header?.type = header?.sections[section]
header?.sectionTitleLabel.text = header?.sections[section].rawValue
return header
}
顺便说一下,我们首先在 loadNibNamed 属性的末尾声明了该属性,因为它返回一个 AnyObjects 数组,并且由于我的 Nib 文件仅包含一个包含标签和按钮的 UIView,所以我只需要其中的第一个也是唯一的项目数组。感谢我的导师 James 解决了这个问题!
关于swift - 在自定义 tableView 单元格上使用 contentView 属性(作为标题传递)如何防止它使自定义属性无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37145411/