JP1*_*971 2 objective-c draggable uiimageview ios4
我有一个可拖动的视图,我已使用以下代码设置:
#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;
}
Run Code Online (Sandbox Code Playgroud)
如何将此视图捕捉到网格?从广义的角度来看,我理解我可以在touchesEnded方法调用中偏移新位置.但是,当我尝试实现这个时,我正在碰壁砖.
提前感谢您对此问题的任何帮助.
jni*_*nic 12
在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);
Run Code Online (Sandbox Code Playgroud)
这会导致您的视图在拖动时"捕捉".
归档时间: |
|
查看次数: |
4782 次 |
最近记录: |