首先看看效果,我只是做了一个demo
里面的view我只是用了一个很普通的label来代表,要具体用其他控件可以随意
上过程了
首先下面我建立了一个controller 里面包含了一个UITableview 上面红色范围内的是tableView的HeaderView 下面重复的很多文字是Cell
controller 我就不细说了 把代码展示出来
TestViewController.swift
import UIKit
class TestViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var header = Bundle.main.loadNibNamed("TestTableViewHeaderView", owner: nil, options: nil)!.last as! TestTableViewHeaderView
convenience init() {
self.init(nibName: "TestViewController", bundle: Bundle.main)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "TestTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "TestTableViewCell")
tableView.estimatedRowHeight = 50
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedSectionHeaderHeight = 50
tableView.sectionHeaderHeight = UITableViewAutomaticDimension
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension TestViewController:UITableViewDataSource,UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TestTableViewCell") as! TestTableViewCell
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return header
}
}
extension TestViewController:UIScrollViewDelegate{
func scrollViewDidScroll(_ scrollView: UIScrollView) {
header.refreshFloatViewFrame()
}
}
cell的代码我就不用展示了 那个无所谓的 下面展示header的代码
class TestTableViewHeaderView: UIView {
@IBOutlet weak var floatViewConstainerView: UIView!
@IBOutlet weak var floatView: UILabel!
func refreshFloatViewFrame() {
if floatView.superview == floatViewConstainerView && floatViewConstainerView.window != nil {
(UIApplication.shared.delegate as! AppDelegate).window!.addSubview(floatView)
}
floatView.bounds = floatViewConstainerView.bounds
var directionCenter = floatViewConstainerView.getPositionInWindow(CGPoint(x: floatView.bounds.width/2, y: floatView.bounds.height/2))
if directionCenter != nil {
directionCenter?.y = (directionCenter!.y < 42 ? 42 : directionCenter!.y)
}else{
directionCenter = CGPoint(x: UIScreen.main.bounds.width/2, y: 42)
}
floatView.center = directionCenter!
}
}
headerView的布局文件不重要 也给看一下吧
当然 你要用的话还得添加一些代码,比如说这个controller的appear和disappear 你必须要把这个浮动的view给放回去 你肯定是需要在HeaderView里面写两个函数实现一下的
本人很希望能够与更多人共享知识,我的做法有可能不是很好,希望有更好的办法的时候来评论说一下,让大家都能够知道更好的方法,转载请注明出处