如何动态增加基于滚动的UITableview的高度

问题描述:

我想在用户滚动到顶部时增加UITableView的高度,当用户滚动到底时降低高度。 我已经通过这个代码如何动态增加基于滚动的UITableview的高度

if scrollView == tableView { 
    print(scrollView.contentOffset.y) 
    let height: CGFloat = scrollView.contentOffset.y+200 
    let maxHeight: CGFloat = self.view.bounds.size.height - 64 
    let minHeight:CGFloat = 200 
    if height < maxHeight && height > minHeight { 
     UIView.animateWithDuration(0.25, animations: {() -> Void in 
      self.tblHeightCons.constant = height 
      self.view.setNeedsUpdateConstraints() 
      }) 
     } 

} 

https://drive.google.com/file/d/0B9WA3RAMmfrKQlBVOG9NaEllRTQ/view

但我不希望移动内容..

我用下面的方式实现这一目标的最佳方式,设置做这种情况你动态高度到tableview并在tableView:numberOfRowsInSection:方法中为scrollview设置contentSize。

_commentsTable.frame = CGRectMake(self.commentsTable.frame.origin.x, self.commentsTable.frame.origin.y, self.commentsTable.frame.size.width,cellDynamicHeight*_commentArray.count) ; 
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width, self.scrollView.frame.size.height+kConstantHeight); 
+0

请观看上传的视频。 –

+1

@SalmanGhumsani如果你想这样做[链接](https://drive.google.com/file/d/0B2anHjlVQmm_aDExLUhXYllXVEk/view?usp=sharing)使用parallaxheader(https://www.cocoacontrols.com/ controls/vgparallaxheader) –

更新。它实现了视频中的效果,并禁止滚动范围时移动的内容,并在滚动范围外时启用移动的内容。快速滚动问题也是固定的:

public func scrollViewDidScroll(_ scrollView: UIScrollView) { 
    let maxHeight: CGFloat = self.view.bounds.size.height - 64 
    let minHeight:CGFloat = 200 
    var height = self.tblHeightCons.constant + scrollView.contentOffset.y 

    if height > maxHeight { 
     height = maxHeight 
    } 
    else if height < minHeight { 
     height = minHeight 
    } 
    else{ 
     scrollView.contentOffset = CGPoint(x: 0, y: 0) 
    } 

    self.tblHeightCons.constant = height 
} 
+0

当我们快速滚动时,它无法伸手到顶部。 –

+0

@SalmanGhumsani,代码被更新以解决“伸手”问题。请再试一次。 –

这将根据tableview高度自动处理scrollview和tableview。

@IBOutlet weak var heightConstraint: NSLayoutConstraint!// tableView height constraint 
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { 
       self.heightConstraint.constant = tableView.contentSize.height 
      }