
UIView *first = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 100, 100)]
first.backgroundColor = [UIColor redColor]
[self.view addSubview:first]
// 初始化第二个view并添加到当前控制器的view上;
UIView *second = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)]
second.backgroundColor = [UIColor greenColor]
[self.view addSubview:second]
// 设置第一个view到最上层
[self.view bringSubviewToFront:first]
// 初始化第一个view并添加到当前控制器的view上;
UIView *first = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 100, 100)]
first.backgroundColor = [UIColor redColor]
[self.view addSubview:first]
// 初始化第二个view并添加到当前控制器的view上;
UIView *second = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)]
second.backgroundColor = [UIColor greenColor]
[self.view addSubview:second]
// 初始化第三个view并添加到当前控制器的view上;
UIView *third = [[UIView alloc] initWithFrame:CGRectMake(70, 70, 100, 100)]
third.backgroundColor = [UIColor yellowColor]
[self.view addSubview:third]
[self.view sendSubviewToBack:second]
// 设置第二个view到最下层
[self.view sendSubviewToBack:second]
// 初始化第一个view并添加到当前控制器的view上;
UIView *first = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 100, 100)]
first.backgroundColor = [UIColor redColor]
[self.view addSubview:first]
// 初始化第二个view并添加到当前控制器的view上;
UIView *second = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)]
second.backgroundColor = [UIColor greenColor]
[self.view addSubview:second]
// 初始化第三个view并添加到当前控制器的view上;
UIView *third = [[UIView alloc] initWithFrame:CGRectMake(30, 70, 100, 100)]
third.backgroundColor = [UIColor yellowColor]
[self.view addSubview:third]
// 设置第一个view在第一层;第二个在第三层;第三个在第四层;第四个在第二层
first.layer.zPosition = 1 // red
second.layer.zPosition = 3// green
third.layer.zPosition = 2 // hello
tableview的实现原理:1.给view添加重用Id要用的时候就从重用缓存池里找可以重用的view如果没有就创建一个添加到缓存池中
2.把屏幕外不可见的view去掉放进可重用池中
本文就是简单实现这个可重用功能,创建一个单个view为屏幕大小,只需要2个view就可以无限滑动的小demo
首先需要写一个一个dataSourse的协议供外部使用
只是简单的实现可重用功能,所以不需要动态添加view,数量和大小都写死了,这个set就相当于缓存池,这里用array也可以,但是由于查找可重用view是随机存取不需要顺序存储所以没必要用array,判断和决定一个view是否可重用需要一个标志,这里就用view自带的tag来处理了,当tag为1时代表可重用(当前不显示在界面上),为0为不可重用(已显示在界面上)
之后需要在初始化后就添加一个view,这里创建了一个first标签用来判断是不是初始化,因为layoutsubviews不只会调用一次,而且我尝试的时候发现是手指移动距离等于屏幕宽度的时候正好会调用一次(一开始没注意这个问题被坑了好久)
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
//获取每次调用该方法相对上次调用时的手指偏移量
let offset = (touches.first?.previousLocation(in: self).x)! - (touches.first?.location(in: self).x)!
//记录当前屏幕左边到原点的距离
contentOffset += offset
先来新建一个自定义的View,继承自UIView
新建一个xib文件
在这里,为了更好地识别,我们把这个xib的名字命名成我们之前新建的那个view子类。
更改xib的File's Owner class,指向我们创建好的class
为xib中已存在的view绑定IBOutlet,命名为contentView。类比tableview cell中content view的作用。
在CustomView.m中实现加载Content View
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder]
if (self) {
[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil]
self.contentView.frame = self.bounds
[self addSubview:self.contentView]
}
return self
}
在Content View中任意地添加子view,添加约束,愉快地玩耍吧~
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)