@interface APLMoveMeView (){ @private CGPoint startPoint;}@end@implementation APLMoveMeView@synthesize placardView;//@synthesize nextDisplayStringIndex;- (void)setupPlaceCardView:(APLPlacardView*)_placecardViews{ self.placardView = _placecardViews;}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {// We only support single touches, so anyObject retrieves just that touch from touches.UITouch *touch = [touches anyObject];// Only move the placard view if the touch was in the placard view.if ([touch view] != self.placardView) {// In case of a double tap outside the placard view, update the placard's display string.if ([touch tapCount] == 2) {[self setupNextDisplayString];}return;} CGPoint point = [[touches anyObject] locationInView:self]; startPoint = point; // Animate the first touch.CGPoint touchPoint = [touch locationInView:self];[self animateFirstTouchAtPoint:touchPoint];}- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {UITouch *touch = [touches anyObject];// If the touch was in the placardView, move the placardView to its location.if ([touch view] == self.placardView) {//CGPoint locationss = [touch locationInView:self];//self.placardView.center = locationss;//計算位移=當前位置-起始位置 CGPoint point = [[touches anyObject] locationInView:self];// float dx = point.x - startPoint.x; float dy = point.y - startPoint.y; //計算移動後的view中心點 CGPoint newcenter = CGPointMake(startPoint.x, self.center.y + dy); /* 限制使用者不可將視圖托出螢幕 */ float halfx = CGRectGetMidX(self.bounds); //x座標左邊界 newcenter.x = MAX(halfx, newcenter.x); //x座標右邊界 newcenter.x = MIN(self.superview.bounds.size.width - halfx, newcenter.x); //y座標同理 float halfy = CGRectGetMidY(self.bounds); newcenter.y = MAX(halfy, newcenter.y); newcenter.y = MIN(self.superview.bounds.size.height - halfy, newcenter.y); //移動view self.placardView.center = newcenter; return;} }- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {UITouch *touch = [touches anyObject];// If the touch was in the placardView, bounce it back to the center.if ([touch view] == self.placardView) {/* Disable user interaction so subsequent touches don't interfere with animation until the placard has returned to the center. Interaction is reenabled in animationDidStop:finished:. */self.userInteractionEnabled = NO;[self animatePlacardViewToCenter];return;}}
使用ios內建執行個體MoveMe,來實現圖片的拖動,限制拖動在螢幕內。下面是更改的部分代碼: