大家可能注意到有些tableView的顶部图片,会随着你拉伸而跟着拉伸变大。
一种思路是将图片放置tableView的tableHeaderView上当tablview下移改变图片的frame达到效果。当然这个效果特别简单,只是单纯试试简书。
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
lazy var myTableView : UITableView! = {
var tableView = UITableView.init(frame: self.view.frame,style:UITableViewStyle.plain)
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "mycell")
return tableView
}()
var headerImageView:UIImageView?
var headerView:UIView?
var headerViewHeight:CGFloat = 0.0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupUI()
}
func setupUI(){
headerView = UIView.init(frame: CGRect(x:0,y:0,width:self.view.frame.width,height:300))
headerViewHeight = headerView!.frame.height;
self.view.addSubview(headerView!)
headerImageView = UIImageView.init(frame: headerView!.frame)
headerImageView?.image = UIImage.init(named: "bg-mine")
headerView?.addSubview(headerImageView!)
myTableView.tableHeaderView = headerView
self.view.addSubview(myTableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "mycell", for: indexPath)
cell.textLabel?.text = "测试"
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let contentOffSetY = scrollView.contentOffset.y
if contentOffSetY < 0 {
var rect = headerView?.frame
rect?.size.height = headerViewHeight - contentOffSetY
let headerViewWidth = headerView?.frame.size.width
rect?.size.width = headerViewWidth!*(headerViewHeight-contentOffSetY)/headerViewHeight
rect?.origin.x = -((rect?.size.width)! - headerViewWidth!)/2
rect?.origin.y = contentOffSetY
headerView?.frame = rect!
headerImageView?.frame = rect!
}
}
}
网友评论