iOS:UIView的transform屬性以及拖拽view的實現,uiviewtransform
一,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