IBOutletCollection set ordering in Interface Builder

18,164

Solution 1

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

Solution 2

I ran with cduhn's answer and made this NSArray category. If now xcode really preserves the design-time order this code is not really needed, but if you find yourself having to create/recreate large collections in IB and don't want to worry about messing up this could help (at run time). Also a note: most likely the order in which the objects were added to the collection had something to do with the "Object ID" you find in the Identity Inspector tab, which can get sporadic as you edit the interface and introduce new objects to the collection at a later time.

.h

@interface NSArray (sortBy)
- (NSArray*) sortByObjectTag;
- (NSArray*) sortByUIViewOriginX;
- (NSArray*) sortByUIViewOriginY;
@end

.m

@implementation NSArray (sortBy)

- (NSArray*) sortByObjectTag
{
    return [self sortedArrayUsingComparator:^NSComparisonResult(id objA, id objB){
        return(
            ([objA tag] < [objB tag]) ? NSOrderedAscending  :
            ([objA tag] > [objB tag]) ? NSOrderedDescending :
            NSOrderedSame);
    }];
}

- (NSArray*) sortByUIViewOriginX
{
    return [self sortedArrayUsingComparator:^NSComparisonResult(id objA, id objB){
        return(
            ([objA frame].origin.x < [objB frame].origin.x) ? NSOrderedAscending  :
            ([objA frame].origin.x > [objB frame].origin.x) ? NSOrderedDescending :
            NSOrderedSame);
    }];
}

- (NSArray*) sortByUIViewOriginY
{
    return [self sortedArrayUsingComparator:^NSComparisonResult(id objA, id objB){
        return(
            ([objA frame].origin.y < [objB frame].origin.y) ? NSOrderedAscending  :
            ([objA frame].origin.y > [objB frame].origin.y) ? NSOrderedDescending :
            NSOrderedSame);
    }];
}

@end

Then include the header file as you chose to name it and the code can be:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Order the labels based on their y position
    self.labelsArray = [self.labelsArray sortByUIViewOriginY];
}

Solution 3

Not sure when this changed exactly, but as of Xcode 4.2 at least, this no longer seems to be a problem. IBOutletCollections now preserve the order in which the views were added in Interface Builder.

UPDATE:

I made a test project to verify that this is the case: IBOutletCollectionTest

Solution 4

I found that Xcode sorts the collection alphabetically using the ID of the connection. If you open the version editor on your nib file you can easily edit the id's (making sure they are unique otherwise Xcode will crash).

<outletCollection property="characterKeys" destination="QFa-Hp-9dk" id="aaa-0g-pwu"/>
<outletCollection property="characterKeys" destination="ahU-9i-wYh" id="aab-EL-hVT"/>
<outletCollection property="characterKeys" destination="Kkl-0x-mFt" id="aac-0c-Ot1"/>
<outletCollection property="characterKeys" destination="Neo-PS-Fel" id="aad-bK-O6z"/>
<outletCollection property="characterKeys" destination="AYG-dm-klF" id="aae-Qq-bam"/>
<outletCollection property="characterKeys" destination="Blz-fZ-cMU" id="aaf-lU-g7V"/>
<outletCollection property="characterKeys" destination="JCi-Hs-8Cx" id="aag-zq-6hK"/>
<outletCollection property="characterKeys" destination="DzW-qz-gFo" id="aah-yJ-wbx"/>

It helps if you first order your object manually in the Document Outline of IB so they show up in sequence in the the xml code.

Solution 5

Not as far as I am aware.

As a workaround, you could assign each of them a tag, sequentially. Have the buttons range 100, 101, 102, etc. and the labels 200, 201, 202, etc. Then add 100 to the button's tag to get its corresponding label's tag. You can then get the label by using viewForTag:.

Alternatively, you could group the corresponding objects into their own UIView, so you only have one button and one label per view.

Share:
18,164

Related videos on Youtube

gebirgsbärbel
Author by

gebirgsbärbel

Updated on November 16, 2020

Comments

  • gebirgsbärbel
    gebirgsbärbel over 3 years

    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) and a group of UILabels (which display the score). I want to make sure that the label directly over the button updates the score. I figured that it is easiest to access them by index. Unfortunately even if I add them in the same order, they do not always have the same indexes. Is there a way in Interface Builder to set the correct ordering.

  • gebirgsbärbel
    gebirgsbärbel almost 13 years
    I already knew about the first solution. The problem is, that I am really hoping there is a way to do it in interface builder that works repeatedly and not only with some good luck. The reason for this is, that we try to do a project, where we teach school girls to program a little quiz in three days. As they are not very experienced, the amount of coding required should be limited. Solution number 2 will not work, as the items are not directly next to each other, or is it possible to have one large view that overlays the other view without getting problems with receiving input events?
  • gebirgsbärbel
    gebirgsbärbel almost 13 years
    this is a nice idea, only you should maybe change the code to compare to x in your first if-statement
  • cduhn
    cduhn almost 13 years
    Well, this example only demonstrates how to sort by y position. You're right that you'll need to tweak the comparator if you want to sort by x.
  • Grav
    Grav about 12 years
    return [[NSNumber numberWithFloat:[obj1 frame].origin.x] compare:[NSNumber numberWithFloat:[obj2 frame].origin.x]]; - this will sort by x
  • Nick Lockwood
    Nick Lockwood about 12 years
    For the benefit of new visitors to this question, Xcode now appears to reliably preserve the order of IBOutletCollection views.
  • cduhn
    cduhn about 12 years
    Sweet! Can you confirm that it works in the simulator and on the device? Also, does it work if you run the app on older OS versions?
  • gebirgsbärbel
    gebirgsbärbel about 12 years
    Are you sure that this is always the case and was not just accidentally true. Because in some cases the order was just fine and as long as I would not change anything it would stay this way.
  • Nick Lockwood
    Nick Lockwood about 12 years
    Well, in every case I've tried it in the last few months (which is several), the IBOutletCollection retains the view order as being whatever order I connected them in IB, which is what I'd expect it to do. I also vaguely recall that this wasn't the case the first time I tried them a year or so ago. So either it didn't used to work and now does, or it always worked this way and I just connected them up wrong when I first tried it and then wrongly gave up on IBOutletCollections. Either way though, it seems to work correctly now. Do you have evidence that it doesn't?
  • gebirgsbärbel
    gebirgsbärbel about 12 years
    I did not specifically try it out since last june. But at that time it definitely did not work and mixed up the ordering pretty badly from time to time. Maybe it is really fixed. I will try that out.
  • Nick Lockwood
    Nick Lockwood about 12 years
    Works on simulator and device. I can't confirm for sure that it works on OS versions prior to 4 but I've tested on 4.1 and above and it's fine. I use them for the high scores table in my game, so I'd have noticed pretty quickly if they were in the wrong order ;-)
  • Dan F
    Dan F almost 12 years
    This does not seem to be the case. I am getting a consistent ordering that is only changing if I Remove or add items to the outlet collection, but it is NOT the same order that I added them
  • Nick Lockwood
    Nick Lockwood almost 12 years
    I suppose another possibility is that they are ordered the same as the order of the views in the nib file. Generally when I've used it, the view order and outlet order have been the same.
  • Dan F
    Dan F almost 12 years
    @NickLockwood I have tried making a simple 3x3 button grid for the purposes of making an iPad-type passcode lock for my app, but the order they're in is seemingly totally random. I obviously added them in order (1-9,0) but the order they appear in the array at runtime is 2,7,5,9,8,4,6,1,3,0. That order seems to have absolutely no correlation between the order they were added to the view, the order they were added to the outlet collection, or even any kind of spatial sorting
  • Nick Lockwood
    Nick Lockwood almost 12 years
    I just built a test project to verify that I'm not going mad: charcoaldesign.com/resources/IBOutletCollectionTest.zip - The button order in the outlet collection follows the order in which they were bound. Changing the order of the views makes no difference. If I unbind and rebind an individual view then it changes the order in a predictable way. Can you provide a counter-project to disprove it?
  • gebirgsbärbel
    gebirgsbärbel almost 12 years
    As I already said in my post, I know the solution, but did not want to use it in this specific case: "You could sort the views based on their tag property, but manually setting tags in IB can be rather tedious."
  • ernesto
    ernesto almost 12 years
    Have you also tried in Storyboard editor? At least, I can't get it to work in Storyboard editor of Xcode 4.3.3. Order seems to be mixed up if something in the Storyboard file gets changed.
  • Nick Lockwood
    Nick Lockwood almost 12 years
    This seems like a good solution if you don't trust outlet collection order. Another option is to use numbered outlets for each view (e.g. label0, label1, etc) and then access them using [self valueForKey:[NSString stringWithFormat:@"label%i", index]]; which would let you iterate through them without writing repetitive code.
  • Ivan Dossev
    Ivan Dossev almost 12 years
    Nice, I didn't think of that. Upside is you don't have to create an extra array, just need to make sure all the elements are named correctly. Only thing to consider is how frequently these elements are accessed. Performance with [NSString stringWithFormat:] is slower than looking things up in a predefined array.
  • Nick Lockwood
    Nick Lockwood almost 12 years
    I'm doubtful that accessing UI elements would ever be a performance bottleneck in a real-world application, but if we were to suppose that it was, you could always loop through them once in viewDidLoad and dump the references into an array for subsequent access.
  • Christopher
    Christopher over 11 years
    This code appears to work fine. However, Xcode 4.3.2 appears to order the outlets as they are listed top-to-bottom in the view and so after some tests I will not need to use it but it's good code and worth a +1.
  • Declan McKenna
    Declan McKenna about 11 years
    @NickLockwood I don't think this is the case when using storyboards.
  • abc123
    abc123 about 11 years
    This is not working for views inside of tableviewcells that are not visible. Any way to get position of non-visible views?
  • cduhn
    cduhn about 11 years
    @SKG, if you're talking about static cells that were laid out in a storyboard with no reuse identifiers set, you probably want to sort by [self.tableView indexPathForCell:cell1].row (and possibly .section if your table has more than one). I haven't tried this with static tables, but I assume that static tables don't reuse their cell objects, so it seems like this should work.
  • bbrame
    bbrame almost 11 years
    Sort by y first and then x: if ([label1 frame].origin.y < [label2 frame].origin.y) return NSOrderedAscending; else if ([label1 frame].origin.y > [label2 frame].origin.y) return NSOrderedDescending; else { if ([label1 frame].origin.x < [label2 frame].origin.x) return NSOrderedAscending; else if ([label1 frame].origin.x > [label2 frame].origin.x) return NSOrderedDescending; else return NSOrderedSame; };
  • jhabbott
    jhabbott over 10 years
    @NickLockwood it does reliably preserve the order, but is there a way to actually edit the order in IB or do you have to remove all items and re-add them?
  • Nick Lockwood
    Nick Lockwood over 10 years
    There's no way to insert another item in the list AFAIK. Just remove the links to the outlets and re-bind them in order. You don't actually have to delete the views.
  • infinity26
    infinity26 over 10 years
    Thanks. This helps with a certain [redacted] version of Xcode that introduces an outlet collection ordering bug.
  • Rivera
    Rivera over 10 years
    If you do want to use tags: [array sortedArrayUsingComparator:^NSComparisonResult(UIView * view1, UIView * view2) { return [@(view1.tag) compare:@(view2.tag)]; }];
  • Duncan C
    Duncan C over 10 years
    Hmm. Is this a reliable behavior of the runtime? If it's not documented, then it's not part of the frameworks' contract, and could change in the future. I wouldn't write an app depending on this behavior.
  • Murray Sagal
    Murray Sagal over 9 years
    Xcode 6 seems to remember the order you add items to the outlet collection. I've only tried this from a storyboard.
  • Dmitry
    Dmitry almost 8 years
    The order is not preserved even in XCode 7.3.1. Reopening XCode did break my ordering today. Swift version is array.sortInPlace({ $0.tag < $1.tag })
  • Antzi
    Antzi over 7 years
    Please NEVER do this. Wether it works or not is irrelevant, this is obfuscation, looks like black magic to others developer and could be broken any time !