ios的视图随手指移动

  最近2天在学习CAAnimation,今天突发奇想,视图随手指触摸的实现。

 @interface ViewController (){
    UILabel *lab;
    CGPoint begin;
    //BOOL noL;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //视图允许用户交互  mark这点非常重要,不然不能让触摸事件取到该视图
    lab.userInteractionEnabled = YES;
}

-(void)loadView{
    [super loadView];
    lab = [[UILabel alloc]init];
    lab.frame = CGRectMake(120, 120, 100, 60);
    lab.backgroundColor = [UIColor redColor];
    //lab.text = @"咚咚咚";
    lab.tag = 1 ;
    [self.view addSubview:lab];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch =  touches.anyObject;
    //NSLog(@"%@",touch.view);
    if(touch.view.tag==1){
        begin = [touch locationInView:lab];
        //NSLog(@"11");
    }
}
//
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch =  touches.anyObject;
    NSLog(@"%@",touch.view);
    if(touch.view.tag==1){
        CGPoint point = [touch locationInView:lab];
        //NSLog(@"11");
        //lab.center = point;

       //控制不让视图移动到屏幕外
        CGPoint newCenter = CGPointZero;
        if(point.x-begin.x>0){
            newCenter.x = MIN(self.view.bounds.size.width-lab.bounds.size.width/2, lab.center.x+(point.x-begin.x));
        }else{
            newCenter.x = MAX(lab.bounds.size.width/2, lab.center.x+(point.x-begin.x));
        }
        if(point.y-begin.y>0){
            newCenter.y = MIN(self.view.bounds.size.height-lab.bounds.size.height/2, lab.center.y+(point.y-begin.y));
        }else{
         newCenter.y = MAX(lab.bounds.size.height/2, lab.center.y+(point.y-begin.y));
        }

       //移动视图
        lab.center = newCenter;
    }
    
    }

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end


整体来说还是比较容易实现的,就是几个点需要注意

lab.userInteractionEnabled = YES;  这个坑了我半个小时,网上找了些资料发现的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值