简体   繁体   中英

How to dynamically increase height of UITableview based on scrolling

I want to increase the height of UITableView when user scroll to top and decrease height when user scroll to down. I have done this situation by this code

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

But i don't want to move contents..

Updated . It implements the effect like in videos, and disable the content moving when scrolling in range, and enable the content moving when scrolling out of range. The fast scrolling problem is also fixed:

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
}

The best way i have used following way to achieve this, set your dynamic height to tableview and set contentSize for scrollview in the tableView:numberOfRowsInSection: method.

_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);

This will automatically handle scrollview and tableview in accordance with tableview height.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM