学过了ios手势,我们来通过手势综合起来做一个小游戏,效果如下
核心代码:
屏幕触点的获得
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UITouch *t = [touches anyObject];
CGPoint p = [t locationInView:self.view];
}
点击手势中,判断在左视图还是右视图,同时处理对应的数据 加或减
- (void)tapAction:(UITapGestureRecognizer *)tap{
if ([tap.view.superview isEqual:self.leftView]) {
//把点击到的view删除
[tap.view removeFromSuperview];
self.leftLabel.text = @(self.leftView.subviews.count).stringValue;
}else{
//把点击到的view删除
[tap.view removeFromSuperview];
self.rightLabel.text = @(self.rightView.subviews.count).stringValue;
}
}
触控结束时,讲拖拽视图的父视图转换为左右视图。更新左右视图里的子视图数据
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
if (CGRectContainsPoint(self.leftView.frame, self.dragIV.center)) {
//得到相对于self.view的点
CGPoint oldCenter = self.dragIV.center;
//把相对于self.view的点转换成相对于leftView的点
CGPoint newCenter = [self.view convertPoint:oldCenter toView:self.leftView];
[self.leftView addSubview:self.dragIV];
self.dragIV.center = newCenter;
self.leftLabel.text = @(self.leftView.subviews.count).stringValue;
}
}
详细源代码及图片就自行github下载:
https://github.com/lee727n/drag-game