Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a NSMutableArray of UIView according to their frame.origin.y

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?

like image 987
xGoPox Avatar asked Dec 14 '12 16:12

xGoPox


2 Answers

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];
like image 193
DrummerB Avatar answered Oct 17 '22 02:10

DrummerB


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]]];
like image 30
Luke Avatar answered Oct 17 '22 01:10

Luke