UITableView+在顶端固定的SegmentedControl

问题:如何在屏幕向上滑动的时候,让两个Segment能固定在屏幕顶端。

网上找了一天没找到,自己也想过很多种方案(用tableView+scrollView实现)发现最终体验都很差。然后突然发现,只需要用tableView就够了。

即Header作为tableView的tableHeaderView,segment作为tableView第一个section的header,cell作为tableView第一个section的cell。


1.先在一个ViewController上做一个UITableView,并做好代理

let tableView = UITableView(frame:CGRectMake(0,0,self.view.frame.width,self.view.frame.height), style: UITableViewStyle.Plain)

tableView.dataSource = self

tableView.delegate = self

self.view.addSubview(tableView)

2.把图上的Header区域放在tableHeaderView

let Header = UIView(frame: CGRectMake(0,0,self.view.frame.width,self.view.frame.height))

tableView.tableHeaderView = Header

3.接下来的工作就是在协议里了

func numberOfSectionsInTableView(tableView: UITableView) -> Int {

return 1

}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return 1

}

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

//这个viewForSegment暂时替代那两个segment

let viewForSegment = UIView(frame: CGRectMake(0,0,self.view.frame.width,50))

view.backgroundColor = UIColor.orangeColor()

return view

}

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

return "标题\(section)"

}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

return 500

}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

//这是剩下的那些cells,cell自己定制

let cell = UITableViewCell(reuseIdentifier: "Module_4Cell")

return cell

}


到这里就完成了,主要利用了tableView的section的header会固定在顶端这个特性。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容