要点:
- 1.
Layer
动画 - 2.
hitTest:
方法
改进的地方:
-
view
内各个子view
的点击判断。
代码:
1.给移动view
添加Layer
动画
JHBarrageView *view = [[JHBarrageView alloc] init];
view.frame = CGRectMake(kScreenWidth, 200, 200, 50);
[self.view addSubview:view];
_barrageView = view;
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position.x"];
animation.toValue = @(view.jh_w*0.5);
animation.duration = 10;
animation.repeatCount = 0;
animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = NO;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[_barrageView.layer addAnimation:animation forKey:@"move"];
2.view
的父类添加点击事件
[self.view addGestureRecognizer:({
[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(jhTap:)];
})];
3.点击事件判断处理
- (void)jhTap:(UITapGestureRecognizer *)tap
{
CGPoint clickPoint = [tap locationInView:self.view];
//判断点是否在移动的layer中,这个可以注释掉
//if ([_barrageView.layer.presentationLayer hitTest:clickPoint]) {
//转换点到移动view的动画layer中
CGPoint p = [_barrageView.layer.presentationLayer convertPoint:clickPoint fromLayer:self.view.layer];
//再进行判断
if (CGRectContainsPoint(_barrageView.header.layer.presentationLayer.frame, p)) {
_clickLabel.text = @"点击了头像";
}
else if (CGRectContainsPoint(_barrageView.nameLabel.layer.presentationLayer.frame, p)) {
_clickLabel.text = @"点击了名字";
}
else if (CGRectContainsPoint(_barrageView.textLabel.layer.presentationLayer.frame, p)) {
_clickLabel.text = @"点击了内容";
}
//}
}