如何实现 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;
}
如何将此视图捕捉到网格?从广泛的角度来看,我知道我可以在 TouchsEnded 方法调用中偏移新位置。然而,当我尝试实现这一点时,我遇到了困难。
预先感谢您对此问题的任何帮助。
I have a draggable view that I have set up with the following code:
#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;
}
How do I go about snapping this view to a grid? From a broad viewpoint, I understand that I could offset the new location in a touchesEnded method call. However, I am hitting a brick wall when I try to implement this.
Thanks in advance for any assistance with this issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
touchesMoved
中,在将newcenter
应用到视图之前,将其舍入为网格步长:这将导致视图在拖动时“对齐”。
In
touchesMoved
, before applyingnewcenter
to your view, round it to your grid step size:This will cause your view to "snap" as you drag it.
虽然jnic的答案中的代码在语义上与下面的代码等效,但我认为这段代码更优雅。
这里是伪代码(javaish),
使用这个例子,x上的一个点,比如x=4应该映射到3,但x=5应该映射到6。
although the code in jnic's answer is semantically equivalent to the code below, i think this code is more elegant.
here it is in pseudocode (javaish)
using this example, a point on x like x=4 should map to 3 but x=5 should map to 6.