Swift 下拉图片拉伸效果

RPReplay_Final1590464354.gif
  • VC中添加要拉伸的ImageView
  • 设置TabelView的contentInset的上边距为imageView高度
  • 先添加ImageView再添加TableView
  • 再滑动代理方法中改变ImageView的Frame

代码:


    let PULLDOWNHEIGHT: CGFloat = 120
    
    
    lazy var pullTable: UITableView = {
        let table = UITableView()
        table.backgroundColor = .clear
        table.delegate = self
        table.dataSource = self
        
        //table.contentInsetAdjustmentBehavior = .never
        
        //设置tableView的上边距
        table.contentInset = UIEdgeInsets(top: PULLDOWNHEIGHT, left: 0, bottom: 0, right: 0)
        
        /**
         问题:
         当设置上边距大与163时 tableView 初始位置一直停留在-163
         需要提前设置一个contenOffset
         */
        
        table.contentOffset = CGPoint(x: 0, y: -PULLDOWNHEIGHT)

        return table
    }()
    
    let stretchImg: UIImageView = {
        let img = UIImageView(image: LOIMG("bg"))
        img.contentMode = .scaleAspectFill
        return img
    }()

    
    
    override func setViews() {
        
        view.addSubview(stretchImg)
        stretchImg.snp.makeConstraints {
            $0.top.equalToSuperview().offset(statusBarH + 44)
            $0.left.right.equalToSuperview()
            $0.height.equalTo(PULLDOWNHEIGHT)
        }
        
        view.addSubview(pullTable)
        pullTable.snp.makeConstraints {
            $0.top.equalToSuperview().offset(statusBarH + 44)
            $0.left.right.bottom.equalToSuperview()
            
        }
        
    }
    
    override func setNavi() {
        self.title = "图片拉伸"
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 150
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.contentView.backgroundColor = RANDOMCOLOR()
        return cell
    }

    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let y = scrollView.contentOffset.y
        //处理图片跟随拉伸
        if y <= -PULLDOWNHEIGHT {
            var tempFrame = self.stretchImg.frame
            tempFrame.size.height = -y
            self.stretchImg.frame = tempFrame
        }
        
    }

你可能感兴趣的:(Swift 下拉图片拉伸效果)