如何在一起滚动的 UITableView 顶部添加一个视图,但在滚动后坚持到顶部 [英] How to add a view on top of UITableView that scrolls together, but stick to top after scrolling
问题描述
我有一个高度为 100 像素的 UIView,它位于我的 UITableView 之上.当我向上滚动时,我希望 UIView 与我的 UITableView 一起滚动,就好像它是它的一部分一样.当我的 UIView 的 50 像素被向上滚动隐藏时,我想在继续向上滚动时将 UIView 固定在顶部.如何做到这一点?我尝试使用更改我的 UIView 的顶部 NSLayoutConstraint 常量等于我的 tableview 的内容偏移量,但它们不会以相同的速度滚动.
I have a UIView with height of 100 pixels that's on top of my UITableView. When I scroll up I want the UIView to scroll together with my UITableView as if it's part it. When 50 pixels of my UIView is hidden from scrolling up, I want to pin the UIView at the top while I continue scrolling up. How can this be achieved? I tried using changing my UIView's top NSLayoutConstraint constant equal to my tableview's content offset, but they don't scroll at the same speed.
推荐答案
首先确保你的tableView是grouped
:
First make sure your tableView is grouped
:
self.tableView = UITableView(frame: CGRect(x: 0, y: (self.navigationController?.navigationBar.frame.maxY)!, width: self.view.bounds.size.width, height: (self.view.bounds.size.height - (self.navigationController?.navigationBar.frame.maxY)!)), style: .grouped)
self.tableView.delegate = self
self.tableView.dataSource = self
self.view.addSubview(self.tableView)
然后你需要在你的tableView
的subview
中添加UIView
:
Then you need to add the UIView
into the subview
of your tableView
:
self.myView = UIView()
self.myView.backgroundColor = UIColor.green
self.myView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 100)
self.tableView.addSubview(self.myView)
为 tableView 的第一部分添加高度为 100 的标题,以便您的单元格位于正确的位置:
Add a header of height 100 for your tableView's first section so that your cells are at right place:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 100
}
然后在滚动时调整 UIView
的框架:
Then adjust the frame of your UIView
when scrolling:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.y
if(offset > 50){
self.myView.frame = CGRect(x: 0, y: offset - 50, width: self.view.bounds.size.width, height: 100)
}else{
self.myView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 100)
}
}
演示:
这篇关于如何在一起滚动的 UITableView 顶部添加一个视图,但在滚动后坚持到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!