1

基本上,我正在按 y 值对数组中的对象进行排序(页面最下方位于数组的开头),但我遇到了一些麻烦。我为数组中的所有 UIImageViews 分配了一个值:

for (UIImageView *Blocky in objectsArray){
  [Blocky.layer setValue:[NSString stringWithFormat: @"%f",
                                     Blocky.center.y] forKey:@"value"];
}

因为它是 UIImageView,所以我必须在“Blocky”之后放置图层,否则会出现以下错误:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIImageView 0x3d44880> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key value.'

我的问题是,当我对它进行排序时,我不知道将“.layer”放在哪里,所以我遇到了同样的问题,因为 UIImageViews 不能自己处理键。这是我的排序代码:

NSSortDescriptor *sortDescriptor =
  [[NSSortDescriptor alloc] initWithKey:@"value" ascending:YES];
[objectsArray sortUsingDescriptors:[NSArray
                                    arrayWithObject:sortDescriptor]];
[sortDescriptor release];

在此先感谢,奥齐

4

3 回答 3

0

使用 NSMutableArray sortUsingFunction:context: 方法:

// top of file
static NSInteger compareImageHeights(id image1, id image2, void* context) {
  CGFloat temp = ((UIImageView*)image2).center.y - ((UIImageView*)image1).center.y;
  return (temp>0)?NSOrderedAscending:(temp<0)?NSOrderedDescending:NSOrderedSame;
}
// within file somewhere
[objectsArray sortUsingFunction:compareImageHeights context:NULL];

需要该函数的原因(您不能只使用 sortUsingSelector: 或 sortUsingSortDescriptor:) 是您不能指定 KVC 键来仅将 y 组件标识排序变量。

编辑:更改center.ysize.height.

编辑:哎呀。改size.heightcenter.y. 将类型固定为 UIImageView 而不是 UIImage。似乎 KVC 对象理论上可以支持任意键,但有些会,有些不会。

于 2010-01-18T12:30:26.793 回答
0

为什么不在每个视图上设置标签属性,因为您根据高度创建它们并通过标签检索它们?

于 2010-01-20T17:20:12.723 回答
0

您确定 CALayer 应该接受任意 KVC 密钥吗?这在我看来是错误的。

您不应该将高度提取到结构缓冲区并对其进行qsort吗?

例如

我认为它会是这样的:

//
// before @implementation sections
//
typedef struct __MySortEntry {
  UIImageView* image;
  CGFloat height;
} MySortEntry, *PMySortEntry;

static int compareMySortEntry (const void * a, const void * b)
{
  CGFloat temp =( ((PMySortEntry)a)->height - ((PMySortEntry)b)->height );
  return (temp<0)?-1:(temp>0)?1:0;
}

//
// in @implementation section somewhere
//
NSMutableData* mutable = [[NSMutableData alloc] initWithLength:
  sizeof(MySortEntry)*objectsArray.count];
PMySortEntry entries = (PMySortEntry)mutable.mutableBytes;
for (int c = 0; c < objectsArray.count; c++) {
  entries[c].image = (UIImageView*)[objectsArray objectAtIndex:c];
  entries[c].height = entries[c].image.center.y;
}

qsort(entries, objectArray.count, sizeof(MySortEntry), compareMySortEntry);

for (int c=0; c < objectArray.count; c++) {
  UIImage* imageInSequence = entries[c].image;
  // do something with images **in sequence**
}
[mutable release];

编辑:更改center.ysize.height.

编辑:改size.heightcenter.y. 哎呀。

编辑:将 UIImage 更改为 UIImageView。

于 2010-01-18T12:07:19.000 回答