拖曳是行動裝置上最直覺的操作。以 UIPanGestureRecognizer 搭配 locationInView:,幾行程式碼就能讓任何視圖跟著手指跑。
@synthesize helloWorldLabel;
@synthesize panGestureRecognizer;
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
/* 先建立一個 label 作為拖曳對象 */
CGRect labelFrame = CGRectMake(0.0f, /* X */
0.0f, /* Y */
150.0f, /* 寬 */
100.0f);/* 高 */
self.helloWorldLabel = [[UILabel alloc] initWithFrame:labelFrame];
self.helloWorldLabel.text = @"Hello World";
self.helloWorldLabel.backgroundColor = [UIColor blackColor];
self.helloWorldLabel.textColor = [UIColor whiteColor];
self.helloWorldLabel.textAlignment = NSTextAlignmentCenter;
// UILabel 預設不接收觸摸,必須開啟互動屬性
self.helloWorldLabel.userInteractionEnabled = YES;
[self.view addSubview:self.helloWorldLabel];
// 建立拖拽手勢
self.panGestureRecognizer = [[UIPanGestureRecognizer alloc]
initWithTarget:self
action:@selector(handlePanGestures:)];
// 最小與最大都設為 1,只允許單指拖曳
self.panGestureRecognizer.minimumNumberOfTouches = 1;
self.panGestureRecognizer.maximumNumberOfTouches = 1;
[self.helloWorldLabel addGestureRecognizer:self.panGestureRecognizer];
}
- (void) handlePanGestures:(UIPanGestureRecognizer*)paramSender{
if (paramSender.state != UIGestureRecognizerStateEnded
&& paramSender.state != UIGestureRecognizerStateFailed){
// 以父視圖的座標系取得手勢位置,直接指派給 center
CGPoint location = [paramSender locationInView:paramSender.view.superview];
paramSender.view.center = location;
}
}
拖曳前
拖曳後
locationInView: 傳入的是 paramSender.view.superview,因為 center 是相對於父視圖的座標。這一步弄錯,視圖就會跑到莫名其妙的位置。translationInView: 做相對位移、加上慣性甩尾的 velocityInView:,或設定邊界限制,都能讓拖曳手感更自然。