简体   繁体   中英

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?

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

虽然这不是frame.origin.y,但您也可以使用SortDescriptor并将layer.position.y作为键来完成此操作。

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

This is how you would do this in Swift:

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

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

you can get the array of subviews using

yourView.subviews

then you can iterate through each and check each frame.origin.y and do your coding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM