Search code examples
objective-ciosuiviewnsarraysorting

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?


Solution

  • 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];