【问题标题】:How to drag an uiimageview without overlapping views?如何在不重叠视图的情况下拖动 uiimageview?
【发布时间】:2025-11-21 12:40:01
【问题描述】:

我在 superview 中有多个视图。如何在不重叠或接触其他视图的情况下拖动 uiimageview。任何帮助表示赞赏..

【问题讨论】:

  • 您的意思是使用界面生成器进行拖放吗?使用.xib?还是故事板?
  • 也许你可以看到这个:*.com/questions/11650149/…
  • no danny,我在 superview 中添加了两个 imageview。我只需要拖动一个图像视图而不接触/重叠其他..

标签: ios drag-and-drop uiimageview


【解决方案1】:

我已经实现了类似的东西。我在这里发布代码sn-p。 Draggable 是您需要在其他包含图像的类中导入的类。

1) Draggable.h

#import <UIKit/UIKit.h>

@interface Draggable : UIImageView
{
    CGPoint startLocation;
}
@end

2) Draggable.m

#import "Draggable.h"

@implementation Draggable

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    // Retrieve the touch point
    CGPoint pt = [[touches anyObject] locationInView:self];
    startLocation = pt;
    [[self superview] bringSubviewToFront:self];
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
    // Move relative to the original touch point
    CGPoint pt = [[touches anyObject] locationInView:self];
    CGRect frame = [self frame];
    frame.origin.x += pt.x - startLocation.x;
    frame.origin.y += pt.y - startLocation.y;
    [self setFrame:frame];
}

@end

3) ProfilePicViewController.m - 我的图片类

#import "Draggable.h"

UIImageView *dragger;

-(void)viewWillAppear:(BOOL)animated
{
    UIImage *tmpImage = [UIImage imageNamed:@"icon.png"];

    CGRect cellRectangle;
    cellRectangle = CGRectMake(0,0,tmpImage.size.width ,tmpImage.size.height );
    dragger = [[Draggable alloc] initWithFrame:cellRectangle];
    [dragger setImage:tmpImage];
    [dragger setUserInteractionEnabled:YES];

    [self.view addSubview:dragger];

}

您可以在此处将“拖动器”拖动到其他图像上。确保具有适当的图像尺寸。 icon.png 的大小为 48X48。所以只要有适合您屏幕的图像大小即可。

希望这可以帮助你。

【讨论】: