如何在UITableView上添加一个视图,滚动到一起,但在滚动后保持顶部
我有一个高度为100像素的UIView,位于我的UITableView之上。当我向上滚动时,我想让UIView与我的UITableView一起滚动,就好像它是它的一部分。当我的UIView的50个像素被隐藏起来时,我想在顶端固定UIView,同时继续向上滚动。这怎么能实现?我尝试使用改变我的UIView的顶部NSLayoutConstraint常量等于我的tableview的内容偏移,但他们不以相同的速度滚动。如何在UITableView上添加一个视图,滚动到一起,但在滚动后保持顶部
你需要的是实现您的tableView的viewForHeader inSection
方法(记住,让您的ViewController实现tableviewDelegate协议),一旦你得到它,你应该将tableViewStyle设置为UITableViewStylePlain
,如果你分享你的代码对更多帮助感兴趣。
如果我理解正确找你问题,你可以通过实现表视图scrollViewDidScroll:
方法这样
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
static CGFloat previousOffset;
CGRect rect = self.yourUIView.frame;
//NSLog you'r UIView position before putting any condition
// NSLog(@"Origin %f",rect.origin.y);
rect.origin.y += previousOffset - scrollView.contentOffset.y;
previousOffset = scrollView.contentOffset.y;
//assuming you'r UIView y position starts from 0
//Before setting the condition please make sure to run without any
//condition if not working
if(rect.origin.y>=-50 && rect.origin.y<=0){
self.yourUIView.frame = rect;
}
}
希望它可以帮助做到这一点...
的风格忘记提到我的代码在Objective C中,因为我不知道swift ... –
第一确保你的tableView是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)
然后,你需要将UIView
添加到的subview
您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)
添加高度100的标题为您的tableView的第一部分,使您的电池是在正确的地方:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 100
}
然后在滚动时调整您的UIView
的帧:
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)
}
}
演示:
你应该看看这个答案:http://*.com/a/17583567/6203030你正在寻找的是的tableView –