Xcode - 考虑到改变的基础 x/y 位置舍入到最接近的 X 值

Xcode - Round to closest X value considering altered base x/y positions

我目前正在开发一个 UICollectionViewLayout,它或多或少类似于 Garageband iPad 应用程序 - 具有可重复使用的 decoration/supplementary 视图。

主要功能之一是网格线对齐 - 这将使您能够将 GREEN 单元格的 X/Y 帧位置对齐到最近的 horizontal/vertical 网格线。

我遇到的问题是,基本 X/Y 位置不是从 0,0 开始,因为我有一个浮动列和浮动行 - 所以我的捕捉计算是错误的,因为它不考虑浮动 row/floating 列 width/height.

这是一张说明我的问题的图片:

这是我计算 snapped 位置的代码:

CGPoint cellTopLeft = self.frame.origin;
CGFloat gridlineWidth = 30;
CGFloat floatingColumnWidth = 120; // width of the floating left column
CGFloat floatingRowHeight = 100; // height of the floating top row
CGFloat rowHeight = 100; // height of rows on the left (table 0, table 1, table 2, etc)

float snapped_x = [self closest:cellTopLeft.x toValue:gridlineWidth];
float snapped_y = [self closest:cellTopLeft.y toValue:rowHeight];

- (float)closest:(float)input toValue:(float)value {
    return value * floorf((input / value) + 0.5);
}

正如你在我主动拖动的"Grand 0"绿色单元格看到的,位置是错误的。

谢谢@zrzka - 有时看似复杂的错误可能是最容易解决的问题,只是需要多一双眼睛。

解决方案是:

float snapped_x = [self closest:cellTopLeft.x - floatingColumnWidth toValue:gridlineWidth] + floatingColumnWidth
float snapped_y = [self closest:cellTopLeft.y - floatingRowHeight toValue:rowHeight] + floatingRowHeight;