创建一个可移动的视图,让视图随着鼠标的移动而移动

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;//触摸取消(主要用于突发事件,此次触摸失效,例如来电话了,电话界面弹出,用户此次触摸被取消)

可以根据这几个方法对一些触摸事件进行处理。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值