iOS開發(fā)--MKMapView添加UIPanGestureRecognizer
來源:程序員人生 發(fā)布時間:2015-02-10 08:17:44 閱讀次數(shù):5481次
當(dāng)我們想給MKMapView添加拖動手勢時,第1個想法多是這樣:
- (void)viewDidLoad
{
//....
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[self.mapView addGestureRecognizer:panGesture];
}
- (void)handlePan:(UIPanGestureRecognizer*) recognizer
{
NSLog("handlePan");
}
運行程序,然后拖動地圖,我們會發(fā)現(xiàn),控制臺并沒有打印任何的“handlePan”,也就是說手勢辨認(rèn)處理函數(shù)handlePan歷來沒有被履行。后來在stackoverflow上找到了答案,正確的解決方法以下:
- (void)viewDidLoad
{
//......
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
panGesture.delegate = self;
[self.mapView addGestureRecognizer:panGesture];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
- (void)handlePan:(UIPanGestureRecognizer*) recognizer
{
NSLog("handlePan");
}
對照1下前后兩段程序,后1段程序?qū)κ謩荼嬲J(rèn)的代理進行了賦值,并實現(xiàn)了shouldRecognizeSimultaneouslyWithGestureRecognizer代理方法。
分析1下第2段代碼運行成功的緣由:MKMapView內(nèi)部實現(xiàn)時,已添加了1個UIPanGestureRecognizer,而這里我們又添加了另外1個UIPanGestureRecognizer,也就是說同1個MKMapView有兩個相同類型的手勢辨認(rèn),但是運行時內(nèi)部默許相同類型的手勢辨認(rèn)只有1個會得到處理,所以第1段代碼始終沒有輸出handlePan。幸虧UIPanGestureRecognizerDelegate提供了gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer方法,該方法返回YES時,意味著所有相同類型的手勢辨認(rèn)都會得到處理。
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機掃描二維碼進行捐贈