Sort NSMutableArray UIView according to their frame.origin.y

I would like to sort NSMutableArray from UIViews according to their frame.origin.y, I want the bottom view with y to be first, etc. It is possible that two UIViews have the same origin. Is there an existing method for this?

+6
source share
4 answers

NSMutableArray has several sorting methods. Select one of them, execute the sort selector, block or function and compare the y values. Here is an example of 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]; 
+15
source

As long as this is not frame.origin.y, you can also do this using SortDescriptor and looking at layer.position.y as a key.

 [array sortedArrayUsingDescriptors:@[[[NSSortDescriptor alloc] initWithKey:@"layer.position.y" ascending:YES]]]; 
+3
source

Here's how you do it in Swift:

 listOfViews.sortInPlace { CGRectGetMinY($0.frame) < CGRectGetMinY($1.frame) } 

Thats all :-) All my love for Swift :-)

+1
source

you can get an array of subtitles using

 yourView.subviews 

then you can iterate over each of them and check each frame.origin.y file and do your own encoding

-2
source

All Articles