答案 0 :(得分:3)
与您分享代码:
而不是使用viewForHeaderInSection
使用cellForRowAt
来创建标题
此外,在为标题单元格设置Xib
时请注意,您必须将标签保留在视图的中心。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var headersIndex = [IndexPath]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "cell", bundle: Bundle.main), forCellReuseIdentifier: "cell")
tableView.register(UINib(nibName: "HeaderTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "HeaderTableViewCell")
}
}
extension ViewController: UITableViewDataSource,UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 5
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 5 {
let cell = tableView.dequeueReusableCell(withIdentifier: "HeaderTableViewCell") as! HeaderTableViewCell
cell.centerLabel.text = "sanjay"
cell.centerLabel.center.x = view.center.x
if !headersIndex.contains(indexPath) {
headersIndex.append(indexPath)
}
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! cell
cell.leftLabel.text = "Message \(indexPath.row)"
cell.rightLabel.text = indexPath.row.description
return cell
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
for i in headersIndex {
if let cell = tableView.cellForRow(at: i) {
if tableView.visibleCells.contains(cell) {
let header = cell as! HeaderTableViewCell
header.centerLabel.center.x = view.center.x + scrollView.contentOffset.x
}
}
}
}
}
答案 1 :(得分:1)