iphone - 拖动特定的 UIImageView

标签 iphone objective-c ios xcode

在我的代码中,我有一个对象数组,这些对象是带有 UIImage 的 UIImageView。

我在 -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 中使用 for 循环将所有对象从数组中逐一移动。

一旦它们被移动到主视图上的不同位置,我希望能够捕获这些对象中的任何一个并将它们移动到其他地方。

我不确定如何最好地做到这一点。有没有一种方法可以使用 touchesbegin 以便我可以只拖动我单击的项目?

基本上,现在有五个 UIImageView,每个都有 UIImage,我试图达到当我点击其中任何一个时它们都能够四处移动的程度。

最佳答案

编辑:John Muchow 将其发布在博客上 here .您应该能够根据自己的目的进行调整。

//UIDraggableImageView.h
#import <UIKit/UIKit.h>

@interface UIDraggableImageView : UIImageView
{
    CGPoint currentPoint;
}

@end

//UIDraggableImageView.m
#import "UIDraggableImageView.h"

@implementation UIDraggableImageView

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

-(void)dealloc {
    [super dealloc];
}

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    // When a touch starts, get the current location in the view
    currentPoint = [[touches anyObject] locationInView:self];
}

- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
    // Get active location upon move
    CGPoint activePoint = [[touches anyObject] locationInView:self];

    // Determine new point based on where the touch is now located
    CGPoint newPoint = CGPointMake(self.center.x + (activePoint.x - currentPoint.x),
                                   self.center.y + (activePoint.y - currentPoint.y));

    //--------------------------------------------------------
    // Make sure we stay within the bounds of the parent view
    //--------------------------------------------------------
    float midPointX = CGRectGetMidX(self.bounds);
    // If too far right...
    if (newPoint.x > self.superview.bounds.size.width  - midPointX)
        newPoint.x = self.superview.bounds.size.width - midPointX;
    else if (newPoint.x < midPointX)  // If too far left...
        newPoint.x = midPointX;

    float midPointY = CGRectGetMidY(self.bounds);
    // If too far down...
    if (newPoint.y > self.superview.bounds.size.height  - midPointY)
        newPoint.y = self.superview.bounds.size.height - midPointY;
        else if (newPoint.y < midPointY)  // If too far up...
        newPoint.y = midPointY;

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

@end

关于iphone - 拖动特定的 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9314045/

相关文章:

iphone - 我需要在xcode4.2中恢复dealloc吗?

iphone - 自定义 UISearchBar 键盘

iphone - performSegueWithIdentifier 触发但不加载下一个 View

ios - 如何以编程方式在 iOS 中并排制作两个 UILabel

ios - CocoaPod 的类别在运行时不可用

ios - 什么时候使用 NSURLSessionDownloadTask 和 NSURLSessionDataTask?

ios - 通过电子邮件发送的 NSDictionary 文件与应用程序中的同一文件不同

iphone - ios 4.3.x 和 5.0 录音后声音中有噪音

iphone - 初始化后如何将 NSManagedObject 关联到上下文?

ios - 如果已登录 LinkedIn App,LinkedIn sdk iOS 会出错