iOS手势之pinch
今天用地图的时候有用到pinch 捏合手势
通过捏合手势动作可以很轻松的来改变视图元素的一个比例
手势的动作状态有如下三种,一般是按照顺序来进行转换的。
1. UIGestureRecognizerStateBegan
2. UIGestureRecognizerStateChanged
3. UIGestureRecognizerStateEnded
一旦捏合手势动作产生了之后,我们就需要在捕获的事件中进行一个页面调整。其中有两个比较重要的变量 scale 和 velocity ,前者是一个比例范围,后者是一个变化速率的,也就是说每次变化的一个像素点。
由于 scale 这个属性的值是每次都在变的,所以我们需要用另外一个变量来保存当前的一个scale的值,这个变量叫做currentScale,这样我们就可以进行一个缩小,变大的视图效果了 。
代码:
- #import "ViewController.h"
- @interface ViewController ()
- @property(nonatomic, strong)UIPinchGestureRecognizer *pinchGestureRecognizer;
- @property(nonatomic, strong)UIView *myView;
- @property(nonatomic, unsafe_unretained)CGFloat currentScale;
- @end
- @implementation ViewController
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- CGRect labelRect = CGRectMake(0, 0, 200, 200);
- self.myView= [[UIView alloc] initWithFrame:self.view.frame];
- self.myView.center = self.view.center;
- self.myView.backgroundColor = [UIColor grayColor];
- //打开view的交互
- self.myBlackLabel.userInteractionEnabled = YES;
- [self.view addSubview:self.myView];
- //创建一个手势
- self.pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinches:)];
- [self.myView addGestureRecognizer:self.pinchGestureRecognizer];
- }
- #pragma mark - 手势事件
- -(void)handlePinches:(UIPinchGestureRecognizer *)paramSender{
- if (paramSender.state == UIGestureRecognizerStateEnded) {
- self.currentScale = paramSender.scale;
- }else if(paramSender.state == UIGestureRecognizerStateBegan && self.currentScale != 0.0f){
- paramSender.scale = self.currentScale;
- }
- if (paramSender.scale !=NAN && paramSender.scale != 0.0) {
- paramSender.view.transform = CGAffineTransformMakeScale(paramSender.scale, paramSender.scale);
- }
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- @end