转自:http://blog.youkuaiyun.com/zhenggaoxing/article/details/44857765
前言
在IOS中,UITableViewController不如UIViewController用的方便,遇到了一个需求:在TableView中添加一个悬浮按钮,不随TableView滑动而滑动。这个需求在UIViewController里面很好实现,给self.view 添加子视图,再把子视图放到最上方即可。可是在表视图控制器中,就很难办,因为控制器中没有作为tableView的父视图的view存在,而把button作为tableView的子视图出现呢,则会随着table的滑动而滑动(⊙﹏⊙b汗,搞了好久都搞不定
)。不过终于搞定了这个问题
。本文原创,转载请注明出处:http://blog.youkuaiyun.com/zhenggaoxing/article/details/44857765
先看看效果吧(先放个蛋糕
)

实现
我们的方案是把button添加为tableVIew的子视图,然后随着table的滑动,动态改变button的高度,实现效果上的“固定”。
首先,初始化button,添加为tableView的子视图,并且放到tableView上方
-
- flowButton=[[UIButton alloc]initWithFrame:CGRectMake(200, 200, 30, 30) ];
- [flowButton setImage:[UIImage imageNamed:@"flowButton"] forState:UIControlStateNormal];
- [self.tableView addSubview:flowButton];
- [self.tableView bringSubviewToFront:flowButton];
- buttonY=(int)flowButton.frame.origin.y;
这里说以下 bringSubviewToFront,就是把子视图移动到顶部的意思,相应的有bringSubviewToBack。看一下官网描述:
Moves the specified subview so that it appears on top of its siblings. |
| This method moves the specified view to the end of the array of views in thesubviews property. |
Parameters |
view | The subview to move to the front. | |
Availability | iOS (2.0 and later) |
翻译一下:将指定的子视图移动到它兄弟视图的顶部,这个方法将指定的视图移动到子视图属性数组的尾部。
到这里,其实悬浮的button已经出现了,接下来就要考虑如何实现固定了。首先,看一下UITableView的继承关系
tableVIew是继承自UIScrollView的,所以这里我们通过<UIScrollViewDelegate> 的
-(
void
)scrollViewDidScroll:(
UIScrollView
*)scrollView 方法和UIScrollView的contentOffset属性来动态调整button的Y值,以实现视觉上的“固定”。
看代码:
- -(void)scrollViewDidScroll:(UIScrollView *)scrollView
- {
- NSLog(@"%d",(int)flowButton.frame.origin.y);
- flowButton.frame = CGRectMake(flowButton.frame.origin.x, buttonY+self.tableView.contentOffset.y , flowButton.frame.size.width, flowButton.frame.size.height);
- }
完整代码:
源代码:https://git.oschina.net/zhengaoxing/IOS_TableView
本文原创,转载请注明出处:http://blog.youkuaiyun.com/zhenggaoxing/article/details/44857765