SoFunction
Updated on 2025-04-12

ios realizes the top spring image effect of tableView

You may notice that some top pictures of tableView will become larger as you stretch. This article shares the "spring" picture on the top of the tableView that is implemented by iOS for your reference. The specific content is as follows

One idea is to place the image on the tableHeaderView of the tableView. When the tableview is moved down and changed the frame of the image to achieve the effect. Of course, this effect is very simple, experts can skip it.

The code is as follows

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

 lazy var myTableView : UITableView! = {
  var tableView = (frame: ,style:)
   = self
   = self
  ((), forCellReuseIdentifier: "mycell")
  return tableView
 }()
 
 var headerImageView:UIImageView?
 var headerView:UIView?
 var headerViewHeight:CGFloat = 0.0
 
 
 override func viewDidLoad() {
  ()
  // Do any additional setup after loading the view, typically from a nib.
  setupUI()
 }

 func setupUI(){
  headerView = (frame: CGRect(x:0,y:0,width:,height:300))
  headerViewHeight = headerView!.;
  (headerView!)
  headerImageView = (frame: headerView!.frame)
  headerImageView?.image = (named: "bg-mine")
  headerView?.addSubview(headerImageView!)
   = headerView
  (myTableView)
  
 }
 

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  return 2
 }
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell:UITableViewCell = (withIdentifier: "mycell", for: indexPath)
  ?.text = "test"
  return cell
 }
 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  return 50
 }
 
 func scrollViewDidScroll(_ scrollView: UIScrollView) {
  let contentOffSetY = 
  if contentOffSetY < 0 {
   var rect = headerView?.frame
   rect?. = headerViewHeight - contentOffSetY
   let headerViewWidth = headerView?.
   rect?. = headerViewWidth!*(headerViewHeight-contentOffSetY)/headerViewHeight
   rect?. = -((rect?.)! - headerViewWidth!)/2
   rect?. = contentOffSetY
   headerView?.frame = rect!
   headerImageView?.frame = rect!
  } 
 }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.