我无法正确交换存储在 IBOutletCollection 中的两个 UIImageView。从概念上讲,我一定做错了什么。
假设我有一个索引数据的 NSMutableArray 和一个索引 UIImageViews 的 NSMutableArray,我希望两个索引数组对应,即 UIImageView 数组的第 n 个索引元素应该反映图像数组中的第 n 个数据元素。
@property (nonatomic, strong) IBOutletCollection(MyImageView) NSMutableArray* myImages;
@property (nonatomic, strong) NSMutableArray* myData;
一开始,我按 x 坐标对 IBOutletCollection 进行排序,以便屏幕上的外观是从左到右的,即索引 0 的元素应该一直出现在左侧,...,一直到屏幕右侧。
NSComparisonResult imageSort(id label1, id label2, void* context)
{
if ([label1 frame].origin.x < [label2 frame].origin.x)
return NSOrderedAscending;
else if ([label1 frame].origin.x > [label2 frame].origin.x)
return NSOrderedDescending;
else { // Determine using y-coordinate
if ([label1 frame].origin.y < [label2 frame].origin.y)
return NSOrderedAscending;
else if ([label1 frame].origin.y > [label2 frame].origin.y)
return NSOrderedDescending;
else
return NSOrderedSame;
}
}
现在,每当我想交换数据数组的两个成员时,我都会确保交换它们的图像,以便每个 UIImageView 始终反映该插槽中的数据。假设我要交换的两个元素具有索引 frontIndex 和 backIndex:
// Switch state data in arrays
Data* sendToBack = myData[frontIndex];
Data* bringToFront = myData[backIndex];
myData[frontIndex] = bringToFront;
myData[backIndex] = sendToBack;
MyImageView* sendToBackImg = myImages[frontIndex];
MyImageView* bringToFrontImg = myImages[backIndex];
myImages[frontIndex] = bringToFrontImg;
myImages[backIndex] = sendToBackImg;
当我尝试为图像数组设置动画或更新时,就会出现问题。看来,当我在索引 0 和 9 处对更新的数组元素调用 animate 或 update 时,实际更新的视图不是位于最左边和左起第 9 个的视图:它们正在更新它们的新位置:
[myImages[frontIndex] animateInWayX]; --> this updates the on-screen view at backIndex
[myImages[backIndex] animateInWayY]; --> this updates the on-screen view at frontIndex
我检查了调试器中的数组,并且确实发生了交换——换句话说,myImages 数组中的 frontIndex 元素确实显示了反映 myData[frontIndex] 处的模型的正确数据,因此视图数组被正确交换,它只是显示在屏幕上的新位置(backIndex 的位置,就好像它没有移动一样)。
我该如何解决?