屏幕上新建兩個view,實(shí)現(xiàn)兩個手指在屏幕上移動兩個view,通過規(guī)則約束兩個view的活動范圍。
關(guān)鍵在于調(diào)用UITouch對象的方法——lacationInView。此方法返回View的相對于根視圖的觸摸位置。返回值是一個CGPoint類型,是一個包含X坐標(biāo)和Y坐標(biāo)的結(jié)構(gòu)體。我讓兩個view在屏幕上下兩個半?yún)^(qū)水平移動。利用CGPointMake來快速初始化新的CGPoint結(jié)構(gòu)體。
- (void)viewDidLoad{ [super viewDidLoad]; self.view.multipleTouchEnabled = TRUE; // Do any additional setup after loading the view, typically from a nib. _view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 40, 40, 40)]; _view1.backgroundColor = [UIColor blueColor]; [self.view addSubview:_view1]; _view2 = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 60, 40, 40)]; _view2.backgroundColor = [UIColor yellowColor]; [self.view addSubview:_view2];}-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event //首次在屏幕上檢測到觸摸時調(diào)用{ NSLog(@"touchesBegan"); for (UITouch *touch in touches) {// NSLog(@" - %p",touch); //獲取根視圖內(nèi)觸摸點(diǎn)的point CGPoint touchPoint = [touch locationInView:self.view]; //約束兩個view的活動范圍 if (touchPoint.y < self.view.frame.size.height/2) { _view1.center = CGPointMake(touchPoint.x, _view1.center.y); }else { _view2.center = CGPointMake(touchPoint.x, _view2.center.y); } }}//以上對觸摸進(jìn)行了初始化,并未處理沿著屏幕移動的觸摸。所以,只需要在touchesMoved方法里調(diào)用touchesBegan的處理方法來改寫移動球拍的邏輯即可。-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event //如果觸摸移動到了新的位置則會調(diào)用此方法{ NSLog(@"touchesMoved"); for (UITouch *touch in touches) {// NSLog(@" - %p",touch); [self touchesBegan:touches withEvent:event]; }}-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event//當(dāng)觸摸離開屏幕調(diào)用此方法{ NSLog(@"touchesEnded"); for (UITouch *touch in touches) { NSLog(@" - %p",touch); }}-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event//如系統(tǒng)決定取消此次觸摸,那可能就不調(diào)用touchesEnded方法了,在這種情況下會調(diào)用touchesCancelled方法{ NSLog(@"touchesCancelled"); for (UITouch *touch in touches) { NSLog(@" - %p",touch); }}
下圖為兩個view可以分別沿著水平方向移動
轉(zhuǎn)載請注明原著來源:http://m.survivalescaperooms.com/marvindev
下一篇介紹iOS開發(fā)筆記之多點(diǎn)觸控(四) 可靠的多點(diǎn)觸控,為每個View分配唯一觸摸對象
新聞熱點(diǎn)
疑難解答
圖片精選