Я разрабатываю собственный tableView с эластичным заголовком, а также с липким заголовком.
Я успешно добился этого, обновив его свойства contentInset и contentOffset. Но после обновления его contentInset прокрутка становится рывками.
Ниже приведен код для того же: я добавил ниже код в метод viewDidLoad
viewController.and вызвал другой метод updateHeaderView
для обновления высоты headerView и позиции y. А kTableHeaderHeight
— это постоянная высота заголовка tableView.
headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: kTableHeaderHeight))
headerView = tableView.tableHeaderView
tableView.tableHeaderView = nil
tableView.addSubview(headerView)
tableView.contentInset = UIEdgeInsets(top: kTableHeaderHeight, left: 0, bottom: 0, right: 0)
tableView.contentOffset = CGPoint(x: 0, y: -kTableHeaderHeight)
В методе updateHeaderView
я добавил код:
var headerRect = CGRect(x: 0, y: -kTableHeaderHeight, width: tableView.bounds.width, height: kTableHeaderHeight)
var insetTop: CGFloat = 0
if tableView.contentOffset.y < -kTableHeaderHeight {
headerRect.origin.y = tableView.contentOffset.y
headerRect.size.height = -tableView.contentOffset.y
insetTop = kTableHeaderHeight
}else if tableView.contentOffset.y >= 0 {
insetTop = 0
}else if tableView.contentOffset.y <= 0{
insetTop = -tableView.contentOffset.y
}
tableView.contentInset = UIEdgeInsets(top: insetTop, left: 0, bottom: 0, right: 0)
tableView.scrollIndicatorInsets = UIEdgeInsets(top: insetTop, left: 0, bottom: 0, right: 0)
headerView.frame = headerRect
И вызываемый выше метод из метода делегата scrollView scrollviewDidScroll
.
После выполнения всего этого липкое и эластичное поведение tableView, как и ожидалось, но прокрутка tableView становится прерывистой. И просто для информации, я не хочу использовать какую-либо стороннюю библиотеку.
Другие методы, используемые для класса
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if (indexPath.row % 2) == 0 {
cell.backgroundColor = UIColor.gray
}else {
cell.backgroundColor = UIColor.white
}
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCell(withIdentifier: "HeaderViewCell") as! HeaderViewCell
return headerCell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 53.0
}
}
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.updateHeaderView()
}
}