我有一个可拖动的 View ,我使用以下代码设置了它:
#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;
}
如何将此 View 捕捉到网格?从广泛的角度来看,我知道我可以在 TouchsEnded 方法调用中偏移新位置。然而,当我尝试实现这一点时,我遇到了困难。
预先感谢您提供有关此问题的任何帮助。
最佳答案
在 touchesMoved
中,在将 newcenter
应用到 View 之前,将其舍入为网格步长:
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);
这将导致您的 View 在拖动时“对齐”。
关于objective-c - 如何实现 UIImageView 的对齐网格功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5421566/