是否可以根据 UIView 的标签对 NSArray 集合进行排序?

发布于 2024-08-28 11:59:19 字数 197 浏览 4 评论 0原文

我见过类似的例子,

[someArray sortUsingSelector:@selector(compare:)];

我正在寻找一个存储 UIView 集合的示例,并且我想根据创建新 UIView 时以编程方式假设的标签按升序或降序对它们进行排序。

如果有人可以提供代码示例或说明,那就太好了

I've seen examples of something like

[someArray sortUsingSelector:@selector(compare:)];

I'm looking for an example that stores a collection of UIViews and I'd like to sort them in ascending or descending order based on tags I assume programatically when a new UIView is created.

If someone could provide a code example or instructions that would be fantastic

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

别忘他 2024-09-04 11:59:19

NSArray 提供了许多对数组进行排序的方法(所有方法都列在 NSArray 文档中的“排序”标题下)。您可以定义一个函数、方法或排序描述符来根据视图的标签进行比较以进行排序。例如,下面是使用 NSSortDescriptor 的实现:

NSSortDescriptor *ascendingSort = [[NSSortDescriptor alloc] initWithKey:@"tag" ascending:YES];
NSSortDescriptor *descendingSort = [[NSSortDescriptor alloc] initWithKey:@"tag" ascending:NO];
NSArray *sortedArray = [someArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:ascendingSort]];

NSArray provides a number of methods to sort an array (all listed under the "Sorting" header in the NSArray docs). You can define a function, a method or a sort descriptor to compare the views based on their tags for sorting. For example, here's an implementation using NSSortDescriptor:

NSSortDescriptor *ascendingSort = [[NSSortDescriptor alloc] initWithKey:@"tag" ascending:YES];
NSSortDescriptor *descendingSort = [[NSSortDescriptor alloc] initWithKey:@"tag" ascending:NO];
NSArray *sortedArray = [someArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:ascendingSort]];
孤独患者 2024-09-04 11:59:19
- (NSComparisonResult)compareTags:(UIView *)view {
    if ([self tag] == [view tag]) return NSOrderedSame;
    if ([self tag] > [view tag]) return NSOrderedDescending;
    return NSOrderedAscending;
}

假设我的顺序正确,也就是说,这种使用的方法必须位于 UIView 上(使用类别很容易完成)。还有其他几种方法可以获得相同的结果,请参阅文档 对数组进行排序

- (NSComparisonResult)compareTags:(UIView *)view {
    if ([self tag] == [view tag]) return NSOrderedSame;
    if ([self tag] > [view tag]) return NSOrderedDescending;
    return NSOrderedAscending;
}

Assuming I got the ordering right, that is, and the methods for this use would have to be on UIView (easily done with a category). There are several other ways of getting the same result, see the docs Sorting Arrays.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文