IOS 拖放缩放

标签 ios drag-and-drop

我有一个包含多个 subview 的 UIView 子类,我想将其拖放到 UICollectionView 中包含的其他几个 UIView 之一。当拖动开始时,我想在拖动期间将拖动的 View 从其当前大小缩放到更小的尺寸(原始尺寸太大而无法方便地选择放置目标而不先缩小它)到目前为止,我有这个:

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.superview bringSubviewToFront:self];
    self.transform = CGAffineTransformMakeScale(0.3f, 0.3f);
    startLocation = ([[touches anyObject] locationInView:self]);
    startLocation = CGPointApplyAffineTransform(startLocation, self.transform);
}

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{  
    CGPoint pt = [[touches anyObject] locationInView:self];
    float dx = pt.x - startLocation.x;
    float dy = pt.y - startLocation.y;
    CGPoint newCenter = CGPointApplyAffineTransform (CGPointMake(self.center.x + dx, self.center.y + dy), self.transform);
    self.center = newCenter;
}

这是一个开始,因为它按我想要的方式缩放拖动的 UIView,并允许我拖动它;但是,拖动的 UIView 不会直接随着鼠标指针移动(我在模拟器上运行)。当图像靠近模拟器屏幕的左上角时,鼠标指针和拖动的 View 在一起;但是当我离开屏幕的右上角时, View 不再直接随着鼠标指针移动;鼠标指针似乎与拖动的 UIView 的移动比例大约为 2:1。

第二个问题是,当拖动结束时,如果项目没有被放下,我需要在将 UIView 重新附加到它的 super View 之前将它恢复到原来的比例,但我还没有完全弄清楚该怎么做。

感谢任何帮助,包括关于更好方法的建议(如果我在这里完全偏离轨道)。 (我知道在隔离放置目标和放置方面还有其他事情要做,但我想我知道那里需要做什么)。

感谢您的指导。

正则表达式

最佳答案

好的,我得到了答案并认为我应该张贴在这里以防其他人需要它。感谢您的早期答复。我看到了以下文章:

How to move a UIImageView after applying CGAffineTransformRotate to it?

这让我想到了以下解决方案。在我的原始代码中,我将变换应用到起始位置,但我没有将它应用到触摸点。所以,这就是我最终解决问题的方法:

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.superview bringSubviewToFront:self];
    self.transform = CGAffineTransformMakeScale(0.2f, 0.2f);
    startLocation = ([[touches anyObject] locationInView:self]);
    startLocation = CGPointApplyAffineTransform(startLocation, self.transform);
}

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint pt = [[touches anyObject] locationInView:self];
    if (!CGAffineTransformIsIdentity(self.transform))
        pt = CGPointApplyAffineTransform(pt, self.transform);
    float dx = pt.x - startLocation.x;
    float dy = pt.y - startLocation.y;
    CGPoint newCenter = CGPointMake(self.center.x + dx, self.center.y + dy);
    self.center = newCenter;
}

因此,当且仅当变换已应用于 UIView 时,才需要将变换应​​用于触摸点。有一次,我将变换应用到触摸点,但没有条件——在那种情况下,整个拖动操作开始时很糟糕,因为变换可能在触摸点还没有出现之前就应用到了触摸点被感动了。不管怎样,上面的代码似乎已经解决了这个问题。

关于IOS 拖放缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14969983/

相关文章:

objective-c - 使用 Cocoa 将图标(mac 和 pc)添加到文件中

ios - 没有这样的模块 'MaterialComponents.MaterialCards_ColorThemer'

cocoa - 将文件拖放到 NSOutlineView 中

java - 如何使 gwt-dnd 允许在拖动时滚动?

objective-c - cocoa中文件路径拖放的实现细节

ios - UITableView:拖放在单元格之间留出空间

ios - 如何获得对象中特定 X 位置的度数?

ios - 移动项目文件夹后 MainStoryboard 消失了

ios - UITableView.automaticDimension 高度即将到来 -1

javascript - 如何使用 javascript/ajax 拖放后更新数据库?