1.首先自定義視圖,繼承自UIView
MoveView.h
@interface MoveView :UIView
@property(nonatomic,assign)CGPoint beginPoint;
//記錄點擊的最初位置
@end
MoveView.m
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch=[touches anyObject];
//記錄下觸摸的最初位置,相對於自身
_beginPoint=[touch locationInView:self];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch=[touches anyObject];
//記錄移動到的位置,此時此時相對於父視圖
CGPoint endPoint=[touch locationInView:self.superview];
[self setFrame:CGRectMake(endPoint.x-_beginPoint.x
, endPoint.y-_beginPoint.y,self.frame.size.width,self.frame.size.height)];
}
2.查UIView的Api可知,UIView繼承自UIResponder,在UIResponder中有下面四個方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;//觸摸開始
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;//觸摸移動
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;//觸摸結束
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;//觸摸取消(主要用於突發事件,此次觸摸失效,例如來電話了,電話界面彈出,用戶此次觸摸被取消)
可以根據這幾個方法對一些觸摸事件進行處理。