大家可能注意到有些tableView的頂部圖片约急,會隨著你拉伸而跟著拉伸變大怪蔑。
一種思路是將圖片放置tableView的tableHeaderView上當(dāng)tablview下移改變圖片的frame達(dá)到效果黍析。當(dāng)然這個效果特別簡單,只是單純試試簡書。
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!
}
}
}