創建一個可移動的視圖,讓視圖隨着鼠標的移動而移動

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;//觸摸取消(主要用於突發事件,此次觸摸失效,例如來電話了,電話界面彈出,用戶此次觸摸被取消)

可以根據這幾個方法對一些觸摸事件進行處理。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章