IBOutletCollection set ordering in Interface Builder

前端 未结 10 1093
我寻月下人不归
我寻月下人不归 2020-11-30 22:20

I am using IBOutletCollections to group several Instances of similar UI Elements. In particular I group a number of UIButtons (which are similar to buzzers in a quiz game) a

10条回答
  •  感动是毒
    2020-11-30 22:54

    EDIT: Several commenters have claimed that more recent versions of Xcode return IBOutletCollections in the order the connections are made. Others have claimed that this approach didn't work for them in storyboards. I haven't tested this myself, but if you're willing to rely on undocumented behavior, then you may find that the explicit sorting I've proposed below is no longer necessary.


    Unfortunately there doesn't seem to be any way to control the order of an IBOutletCollection in IB, so you'll need to sort the array after it's been loaded based on some property of the views. You could sort the views based on their tag property, but manually setting tags in IB can be rather tedious.

    Fortunately we tend to lay out our views in the order we want to access them, so it's often sufficient to sort the array based on x or y position like this:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        // Order the labels based on their y position
        self.labelsArray = [self.labelsArray sortedArrayUsingComparator:^NSComparisonResult(UILabel *label1, UILabel *label2) {
            CGFloat label1Top = CGRectGetMinY(label1.frame);
            CGFloat label2Top = CGRectGetMinY(label2.frame);
    
            return [@(label1Top) compare:@(label2Top)];
        }];
    }
    

提交回复
热议问题