2011-03-24 57 views
2

我有一個可拖動的觀點,我已經設置了用下面的代碼:如何實現捕捉UIImageView的網格功能?

#import <UIKit/UIKit.h> 

@interface DraggableView : UIImageView { 

    CGPoint startLocation; 
} 

@end 

#import "DraggableView.h" 

@implementation DraggableView 

- (id) initWithImage: (UIImage *) anImage 
{ 
    if (self = [super initWithImage:anImage]) 
     self.userInteractionEnabled = YES; 
    return self; 
} 

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event 
{ 
    // Calculate and store offset, and pop view into front if needed 
    CGPoint pt = [[touches anyObject] locationInView:self]; 
    startLocation = pt; 
    [[self superview] bringSubviewToFront:self]; 
} 

- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event 
{ 
    // Calculate offset 
    CGPoint pt = [[touches anyObject] locationInView:self]; 
    float dx = pt.x - startLocation.x; 
    float dy = pt.y - startLocation.y; 
    CGPoint newcenter = CGPointMake(self.center.x + dx, self.center.y + dy); 

    // Set new location 
    self.center = newcenter; 
} 

如何去捕捉這種觀點的電網?從廣泛的角度來看,我知道我可以在touchesEnded方法調用中抵消新位置。但是,當我試圖實現這一點時,我碰到了一堵磚牆。

在此先感謝您對此問題的任何幫助。

回答

11

touchesMoved,應用newcenter到您的視圖,圓到您的網格步長之前:

float step = 10.0; // Grid step size. 
newcenter.x = step * floor((newcenter.x/step) + 0.5); 
newcenter.y = step * floor((newcenter.y/step) + 0.5); 

這將導致您的視圖「嵌入」當你拖動。

4

儘管jnic的答案中的代碼在語義上等同於下面的代碼,但我認爲這段代碼更優雅。

在這裏它是在僞代碼(javaish)

int gridCubeWidth = 3; //for instance 
int gridCubeHeight = 3; 

int newX = Math.Round(oldX/gridCubeWidth) * gridCubeWidth; 
int newY = Math.Round(oldY/gridCubeHeight) * gridCubeHeight; 

使用此實例中,X上的一個點狀X = 4應映射到3,但是X = 5應映射到6