最近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; 这个坑了我半个小时,网上找了些资料发现的