gpt4 book ai didi

iphone - 拖动特定的 UIImageView

转载 作者:搜寻专家 更新时间:2023-10-30 20:21:42 24 4
gpt4 key购买 nike

在我的代码中,我有一个对象数组,这些对象是带有 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com