2012-01-10 2 views
4

나는 끌어서 놓기 메뉴에 영향을 미치려고합니다. 이 문제를 어떻게 해결해야할지 모르겠다. 아마도 누군가이 정확한 효과에 대한 경험이있을 것이다.어떻게 지속적인 드래그 드롭 메뉴 효과를 달성하기 위해?

간단히 말해서 사용자가 메뉴 항목을 터치하면 그래픽이 터치 위치에 나타나기를 원합니다. 터치가 그래픽의 패닝을 제어합니다. 터치를 놓으면 그래픽이 그 자리에 앉아 완전한 알파를 가정합니다.

저는 팬 제스처를 만들고 그래픽을 인스턴스화하는 것에 익숙합니다. 지금까지는 메뉴 항목을 터치 한 그래픽을 만들 수 있습니다. 가장 큰 문제는 어떻게 터치 제스처를 "지나쳐"단일 동작과 연속 동작인지를 파악하는 것입니다.

또한 메뉴 항목이 UIButton 또는 UIImageView 여야합니까?

도움을 주시면 감사하겠습니다. enter image description here

답변

1

나는 이걸 좀 재미있게 보았습니다. 다음 코드는 터치 할 때 버튼에서 이미지를 가져 와서 이미지를 alpha = 0.5로 드래그하고 터치가 alpha = 1.0에서 끝나는 위치에 놓습니다. 그 후에도 계속해서 드래그 할 수 있습니다.

QuartzCore를 가져온 후 새 파일을 만듭니다.

#import <Foundation/Foundation.h> 
#import <QuartzCore/CAGradientLayer.h> 
#import <QuartzCore/CALayer.h> 

@interface DraggableImage : CAGradientLayer 

- (void)draw:(UIImage *)image; 

- (void)moveToFront; 

- (void)appearDraggable; 

- (void)appearNormal; 

@end 

을하고하는 .m 읽어야합니다 : :이 .H 읽어야

#import "DraggableImage.h" 

@implementation DraggableImage 

- (void)draw:(UIImage *)image{ 
    CGRect buttonFrame = self.bounds; 
    int buttonWidth = buttonFrame.size.width; 
    int buttonHeight = buttonFrame.size.height; 
    UIGraphicsBeginImageContext(CGSizeMake(buttonWidth, buttonHeight)); 
    [image drawInRect:self.bounds]; 
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    [newImage drawInRect:self.bounds]; 
} 

- (void)moveToFront { 
    CALayer *superlayer = self.superlayer; 
    [self removeFromSuperlayer]; 
    [superlayer addSublayer:self]; 
} 

- (void)appearDraggable { 
    self.opacity = 0.5; 
} 


- (void)appearNormal { 
    self.opacity = 1.0; 
} 

@end 

이제 기본보기 컨트롤러에 추가 :

#import <UIKit/UIKit.h> 
#import <QuartzCore/QuartzCore.h> 
#import "DraggableImage.h" 

@interface YourViewController : UIViewController{ 
    DraggableImage *heldImage; 
    DraggableImage *imageForFrame[5]; // or however many 
    UIButton *buttonPressed; 
    int imageCount; 
} 
@property (weak, nonatomic) IBOutlet UIButton *imageButton; 
-(IBAction)buildImageLayerForButton:(UIButton *)sender; 
- (void)moveHeldImageToPoint:(CGPoint)location; 
- (CALayer *)layerForTouch:(UITouch *)touch; 

을이 경우에하여 ImageButton이 될 것이다 당신의 사과 단추. 네가 지금.파일을 추가하려면 다음을 추가하십시오 :

@synthesize imageButton; 

#pragma - mark Touches 

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 
    CALayer *hitLayer = [self layerForTouch:[touches anyObject]]; 
    if ([hitLayer isKindOfClass:[DraggableImage class]]) { 
     DraggableImage *image = (DraggableImage *)hitLayer; 

     heldImage = image; 
     [heldImage moveToFront]; 
    } 
    hitLayer = nil; 
    [super touchesBegan:touches withEvent:event]; 
} 

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ 

     if (heldImage) 
     { 
      UITouch *touch = [touches anyObject]; 
      UIView *view = self.view; 
      CGPoint location = [touch locationInView:view]; 
      [self moveHeldImageToPoint:location]; 
     } 

} 

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ 
    if (heldImage) { 
     [heldImage appearNormal]; 
     heldImage = nil; 
    } 
} 

- (void)dragBegan:(UIControl *)c withEvent:ev { 
} 
- (void)dragMoving:(UIControl *)c withEvent:ev { 
    UITouch *touch = [[ev allTouches] anyObject]; 
    CGPoint touchPoint = [touch locationInView:self.view]; 
    [self moveHeldImageToPoint:touchPoint]; 
} 

- (void)dragEnded:(UIControl *)c withEvent:ev { 
    UITouch *touch = [[ev allTouches] anyObject]; 
    CGPoint touchPoint = [touch locationInView:self.view]; 
    [self moveHeldImageToPoint:touchPoint]; 
    [heldImage appearNormal]; 
    heldImage = nil; 
} 



-(IBAction)buildImageLayerForButton:(UIButton *)sender{ 


     DraggableImage *image = [[DraggableImage alloc] init]; 
     buttonPressed = sender; 
     CGRect buttonFrame = sender.bounds; 
     int buttonWidth = buttonFrame.size.width; 
     int buttonHeight = buttonFrame.size.height; 

     image.frame = CGRectMake(120, 24, buttonWidth*3, buttonHeight*3); 
     image.backgroundColor = [UIColor lightGrayColor].CGColor; 
     image.delegate = self; 
     imageForFrame[imageCount] = image; 
     [self.view.layer addSublayer:image]; 
     [image setNeedsDisplay]; 
     [image moveToFront]; 
     [image appearDraggable]; 
     heldImage = image; 
     [self moveHeldImageToPoint:sender.center]; 

     imageCount++; 

} 
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx { 
    UIGraphicsPushContext(ctx); 

    DraggableImage *image = (DraggableImage *)layer; 
    [image draw:[buttonPressed imageForState:UIControlStateNormal]]; 

    UIGraphicsPopContext(); 
} 

- (void)moveHeldImageToPoint:(CGPoint)location 
{ 
    float dx = location.x; 
    float dy = location.y; 
    CGPoint newPosition = CGPointMake(dx, dy); 

    [CATransaction begin]; 
    [CATransaction setDisableActions:TRUE]; 
    heldImage.position = newPosition; 
    [CATransaction commit]; 
} 

- (CALayer *)layerForTouch:(UITouch *)touch 
{ 
    UIView *view = self.view; 

    CGPoint location = [touch locationInView:view]; 
    location = [view convertPoint:location toView:nil]; 

    CALayer *hitPresentationLayer = [view.layer.presentationLayer hitTest:location]; 
    if (hitPresentationLayer) 
    { 
     return hitPresentationLayer.modelLayer; 
    } 

    return nil; 
} 

-(void)viewDidLoad{ 
    [imageButton addTarget:self action:@selector(dragBegan:withEvent:) forControlEvents: UIControlEventTouchDown]; 
    [imageButton addTarget:self action:@selector(dragMoving:withEvent:) forControlEvents: UIControlEventTouchDragInside | UIControlEventTouchDragOutside]; 
    [imageButton addTarget:self action:@selector(dragEnded:withEvent:) forControlEvents: UIControlEventTouchUpInside | UIControlEventTouchUpOutside]; 
    [super viewDidLoad]; 
} 

- (void)viewDidUnload { 
    [self setImageButton:nil]; 
    [super viewDidUnload]; 
} 

Et voila! 버튼을 연결하고, 이미지를 설정하고, 화면 전체에 사본을 던집니다. :)

참고 : 많은 의견을 말하지는 않았지만 질문에 답할 수는 있습니다.

건배!

편집 : -(void)draw:(UIImage *)image{}을 수정하여 이미지의 크기를 올바르게 조정하십시오.

0

당신이 원하는 경우 덕분에 두 번째 그래픽에 터치 기능 (큰 하나) 난 당신이 이미지를 선언하는 당신이 가지고 .H에이

같은 것을 할 수 있다고 생각을 전달하는 것입니다 당신 ' 드래그 앤 dragable 버튼의 이전 점을 기억하는 변수를 떠가는 재

@property(nonatomic, strong) UIImageView* myImage; 
@property float pointX; 
@property float pointY; 

다음 (난 당신이 IOS 5 SDK를 사용 있으리라 믿고있어)하는 .m에서 만약 당신이

myImage = [[UIImageView alloc]initWithImage:@"appleImage.jpg"]; 
myImage.alpha = 0; 

//default UIImageView interaction is disabled, so lets enabled it first 
myImage.userInteractionEnabled = YES; 

[button addTarget:self action:@selector(wasDragged:withEvent:) forControlEvents:UIControlEventTouchDragInside]; 
작업을 수행 할 수 있습니다

한 다음,

- (void)wasDragged:(UIButton *)button withEvent:(UIEvent *)event 
{ 

     self.myImage.alpha = 0.5; 

    UITouch *touch = [[event touchesForView:button] anyObject]; 


    CGPoint previousLocation = [touch previousLocationInView:button]; 
    CGPoint location = [touch locationInView:button]; 
    CGFloat delta_x = location.x - previousLocation.x; 
    CGFloat delta_y = location.y - previousLocation.y; 

    // move button, to keep the dragging effect 
    button.center = CGPointMake(button.center.x + delta_x, 
           button.center.y + delta_y); 

     // moving the image 
     button.center = CGPointMake(button.center.x + delta_x, 
           button.center.y + delta_y); 

    self.pointX = previousLocation.x; 
    self.pointY = previousLocation.y; 

    [button addTarget:self action:@selector(dragRelease:withEvent:) forControlEvents:UIControlEventTouchUpInside]; 
} 

마지막으로 드래그 기능을 사용하면 원래 위치에있는 버튼을 반환 dragRelease 기능을 1

-(void)dragRelease:(UIButton *)button withEvent:(UIEvent *)event 
{ 
    self.myImage.alpha = 1; 
    button.center = CGPointMake(pointX, pointY); 
} 

에 이미지의 알파를 설정하고 당신이있어 완료 : 3

이 그냥 기본적인 아이디어는 어쩌면 이것은 당신이 원하는하지 않습니다,하지만 난이

편집 도움이되기를 바랍니다, 그래도입니다 * 아, 그리고 모든 속성을 종합하는 것을 잊지 마세요. 5.0 이하 SDK를 사용하는 경우 "강력한"속성을 "보유"로 변경할 수 있습니다.

+0

안녕하세요. 촬영 해 주셔서 감사합니다. 두 가지 변경 사항으로 코드를 시도했습니다. UIControlEventTouchDragInside와 UIControlEventTouchDragOutside를 사용하여 더 잘 작동한다고 생각했습니다. 그러나 효과를 얻지 못했습니다. 드래그하면 50 % 불투명 대형 이미지가 아닌 버튼 만 이동합니다. 해제하면 단추가 왼쪽 상단에 던져집니다. 나는 그것을 계속 변경하고 내가 얻을 수있는 것을 볼 것입니다. 추가 코드가 감사하겠습니다. 감사! – user339946

+0

이미지를 하위보기로보기에 추가 했습니까 ?? using [self.view addSubview : myImage];를 사용합니다. ??? –

+0

예. 업로드하거나 공유 할 수있는 작업 코드 샘플이 있습니까? 감사 – user339946

관련 문제