I would like to sort an NSMutableArray of UIViews according to their frame.origin.y, I want the lowest view with y to be first etc. It can be the case that 2 UIViews have the same origin. Is there an existing method for this?
NSMutableArray
has several sorting methods. Pick one of them, implement the sorting selector, block or function and compare the y
values. Here is an example using blocks:
NSComparator comparatorBlock = ^(UIView *obj1, UIView *obj2) {
if (obj1.frame.origin.y > obj2.frame.origin.y) {
return (NSComparisonResult)NSOrderedDescending;
}
if (obj1.frame.origin.y < obj2.frame.origin.y) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
};
[array sortUsingComparator:comparatorBlock];
While this isn't the frame.origin.y, you can also do this by using a SortDescriptor and looking at the layer.position.y as the key.
[array sortedArrayUsingDescriptors:@[[[NSSortDescriptor alloc] initWithKey:@"layer.position.y" ascending:YES]]];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With