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; 這個坑了我半個小時,網上找了些資料發現的