我可以轻松返回标题部分的标题,如:
if(section == 1) {
}
等等
我有这个:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if let UpperView = Bundle.main.loadNibNamed("Head", owner: self, options: nil)?.first as? Head {
let sectionTitle = ["Head0","Head1","Head2"]
var mysection = 0
for sectitile in sectionTitle
{
if(section == mysection)
{
UpperView.lhlHead.text = sectitile
mysection += 1
}
}
return UpperView
}
return nil
}
我想在标题视图的标签中设置Head1,Head2,Head3。
使用它时工作正常:
if(section == 0) {
UpperView.lhlHead.text = "Head0"
} else if(section == 1) {
UpperView.lhlHead.text = "Head1"
} else if(section == 2) {
UpperView.lhlHead.text = "Head2"
}
什么时候使用数组没有看到任何字符串。为什么会这样?
答案 0 :(得分:0)
您的变量mysection
始终设置为0,但会将其与当前部分的数字进行比较,该数字从0到表格中的部分数量不等。因此,支票section == mysection
仅会针对第一部分的标题传递,您只会将标题设置到第一部分的标题中。
相反,此函数为您提供了处理的部分(section: Int
)的编号,并且您有sectionTitle
数组,其中部分编号(数组索引)与部分标题匹配。所以而不是:
if let UpperView = Bundle.main.loadNibNamed("Head", owner: self, options: nil)?.first as? Head {
let sectionTitle = ["Head0","Head1","Head2"]
var mysection = 0
for sectitile in sectionTitle
{
if(section == mysection)
{
UpperView.lhlHead.text = sectitile
mysection += 1
}
}
return headerView
}
return nil
你可以使用它:
if let UpperView = Bundle.main.loadNibNamed("Head", owner: self, options: nil)?.first as? Head {
let sectionTitle = ["Head0","Head1","Head2"]
UpperView.lhlHead.text = sectionTitle[section]
return headerView
}
return nil
另外,不要大写变量名称,所以正确的代码是:
if let upperView = Bundle.main.loadNibNamed("Head", owner: self, options: nil)?.first as? Head {
let sectionTitle = ["Head0","Head1","Head2"]
upperView.lhlHead.text = sectionTitle[section]
return headerView
}
return nil