我为你把这个放在一起。这是如何做到这一点的一个例子。然而,UITableview 并不打算以这种方式使用。您可以看到单元格 0 被您的自定义视图覆盖。从数据源填充表格视图时,您必须考虑到这一点。
import UIKit
class testTableVIewController: UITableViewController {
@IBOutlet var theTableView: UITableView!
var profileView:UIView
required init?(coder aDecoder: NSCoder) {
profileView = UIView(frame: CGRectMake(0,0,500,45))
profileView.backgroundColor = UIColor(red:0.35, green:0.77, blue:0.66, alpha:1)
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.theTableView.addSubview(profileView)
}
override func scrollViewDidScroll(scrollView: UIScrollView) {
profileView.frame = CGRectOffset( profileView.frame, scrollView.contentOffset.x, 0 );
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = theTableView.dequeueReusableCellWithIdentifier("cell")
cell?.textLabel?.text = String(indexPath.row)
return cell!
}
}
您应该做的是,而不是将视图作为表格视图的子视图。
- 创建一个视图。 (为方便起见,我将此称为内容视图)
- 将视图添加到此内容视图。
- 将表格视图添加到内容视图。
只需在内容视图中将视图/表格视图彼此相邻放置。
这将具有滚动表格视图和彼此相邻的静态视图的预期效果。如果想要的效果是表格视图上的浮动视图,则反转步骤 2 和 3。
哦,顺便说一句。如果您在代码中完成所有操作,则更改为这种布局非常容易。只需将您的 tableview 控制器更改为视图控制器并采用 UITablview 协议。
class testTableVIewController: UITableViewController {
class testTableVIewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
然后为 tableview 类添加一个属性。还将其添加到 self.view 的正确位置。还记得将你的绿色视图添加到 self.view
如果你这样做,你根本不需要更改太多代码。