iOS:UIView的transform属性以及拖拽view的实现
程序员文章站
2022-05-01 17:45:48
一,UIView的transform属性的使用
#import "ViewController.h"
@interface ViewCont...
一,UIView的transform属性的使用
#import "ViewController.h" @interface ViewController () @property (weak, nonatomic) IBOutletUIImageView *imageV; @end @implementation ViewController - (void)viewDidLoad { [superviewDidLoad]; } - (IBAction)moveUp:(id)sender { //平移 [UIView animateWithDuration:0.5animations:^{ //使用Make,它是相对于最原始的位置做的形变. //self.imageV.transform = CGAffineTransformMakeTranslation(0, -100); //相对于上一次做形变. self.imageV.transform = CGAffineTransformTranslate(self.imageV.transform,0, -100); }]; } - (IBAction)moveDown:(id)sender { //平移 [UIView animateWithDuration:0.5animations:^{ //使用Make,它是相对于最原始的位置做的形变. //self.imageV.transform = CGAffineTransformMakeTranslation(0, -100); //相对于上一次做形变. self.imageV.transform = CGAffineTransformTranslate(self.imageV.transform,0,100); }]; } - (IBAction)rotation:(id)sender { [UIViewanimateWithDuration:0.5animations:^{ //旋转(旋转的度数, 是一个弧度) //self.imageV.transform = CGAffineTransformMakeRotation(M_PI_4); self.imageV.transform = CGAffineTransformRotate(self.imageV.transform,M_PI_4); }]; } - (IBAction)scale:(id)sender { [UIView animateWithDuration:0.5animations:^{ //缩放 //self.imageV.transform = CGAffineTransformMakeScale(0.5, 0.5); self.imageV.transform = CGAffineTransformScale(self.imageV.transform,0.8,0.8); }]; } @end
二,UIView的touch方法的简单使用,实现拖拽view的效果
#import "RedView.h" @implementation RedView //当开始触摸屏幕的时候调用 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"%s",__func__); } //触摸时开始移动时调用(移动时会持续调用) //NSSet:无序 //NSArray:有序 -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ //NSLog(@"%s",__func__); //做UIView拖拽 UITouch *touch = [touches anyObject]; //求偏移量 = 手指当前点的X - 手指上一个点的X CGPoint curP = [touch locationInView:self]; CGPoint preP = [touchpreviousLocationInView:self]; NSLog(@"curP====%@",NSStringFromCGPoint(curP)); NSLog(@"preP====%@",NSStringFromCGPoint(preP)); CGFloat offsetX = curP.x - preP.x; CGFloat offsetY = curP.y - preP.y; //平移 self.transform =CGAffineTransformTranslate(self.transform, offsetX, offsetY); } //当手指离开屏幕时调用 -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"%s",__func__); } //当发生系统事件时就会调用该方法(电话打入,自动关机) -(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"%s",__func__); } @end