我们先来看一下这个效果,
本人看到这个控件的效果的第一反应是——这个任何初学者应该都会吧,相信绝大多数的开发人员也和我一样,我们再看一张图
在看到这张图的时候,瞬间蒙了,这绝对不是表面这么简单,至少眼见为虚!
然后再根据原文上(http://ios.jobbole.com/83528/)的github地址找源码,对方把实现给封装了,好吧,源码看不到只好自己实现了,再实现之前,我们先聊下面对这个问题时想法。
想法——分析:
1、这里至少有三层,底层黑色label,最上层高亮字体label,以及红色视图view
2、UIView的clipstoBounds 方法应该可以在这里发挥大用
3、同个位置有多层视图,那么要手动设置响应主体,并且这里应该是通过点击去确定点在哪个底层的label上
4、如果用clipstoBounds方法,那么高亮字体的label一定是加到红色视图view上的
5.。。。。。。
6.。。。。。。等等
总之解决问题的过程就像埋坑。
最后,我们来看下实现1.0的核心代码
代码1.视图的创建
- (void)loadCustomView {
NSArray *arrayTitle = @[@"Hello",@"Apple",@"Objc",@"Swift"];
for (int i = 0; i < 4; i++) {
FirstFloorLabel *label1 = [[FirstFloorLabel alloc] initWithFrame:CGRectMake((kWidth - 320)/2 + i*80, 40, 80, 40)];
label1.textColor = [UIColor blackColor];
label1.userInteractionEnabled = YES;
label1.tag = i+10;
label1.textAlignment = NSTextAlignmentCenter;
//label1.backgroundColor = [UIColor grayColor];
label1.text = arrayTitle[i];
[self addSubview:label1];
}
buttonView = [[UIView alloc] initWithFrame:CGRectMake((kWidth - 320)/2, 40, 80, 40)];
buttonView.backgroundColor = [UIColor redColor];
buttonView.layer.cornerRadius = 8;
buttonView.clipsToBounds = YES;
[self addSubview:buttonView];
label2sFatherView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
//label2sFatherView.backgroundColor = [UIColor greenColor];
//label2sFatherView.alpha = 0.5;
[buttonView addSubview:label2sFatherView];
for (int i = 0; i < 4; i++) {
SecondFloorLabel *label2 = [[SecondFloorLabel alloc] initWithFrame:CGRectMake(i*80, 0, 80, 40)];
label2.textColor = [UIColor whiteColor];
label2.textAlignment = NSTextAlignmentCenter;
label2.text = arrayTitle[i];
[label2sFatherView addSubview:label2];
}
}
代码2 动画效果的实现
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
for (UIView *subView in self.subviews) {
CGPoint p = [self convertPoint:point toView:subView];
if ([subView pointInside:p withEvent:event] && [subView isKindOfClass:[FirstFloorLabel class]]) {
[UIView animateWithDuration:0.7 animations:^{
CGPoint p3 = label2sFatherView.center;
CGPoint p1 = buttonView.center;
CGPoint p2 = subView.center;
CGFloat offsetX = p2.x - p1.x;
p3.x -= offsetX;
buttonView.center = subView.center;
label2sFatherView.center = p3;
}];
return subView;
}
}
return [super hitTest:point withEvent:event];
}
完整的实现1.0会稍后上传到github上