IBOutletCollection set ordering in Interface Builder

前端 未结 10 1066
我寻月下人不归
我寻月下人不归 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 23:07

    It seems very random how IBOutletCollection is ordered. Maybe I am not understanding Nick Lockwood's methodology correctly - but I as well made a new project, added a bunch of UILabels, and connected them to a collection in the order they were added to the view.

    After logging, I got a random order. It was very frustrating.

    My workaround was setting tags in IB and then sorting the collections like so:

    [self setResultRow1:[self sortCollection: [self resultRow1]]];
    

    Here, resultRow1 is an IBOutletCollection of about 7 labels, with tags set through IB. Here is the sort method:

    -(NSArray *)sortCollection:(NSArray *)toSort {
        NSArray *sortedArray;
        sortedArray = [toSort sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
            NSNumber *tag1 = [NSNumber numberWithInt:[(UILabel*)a tag]];
            NSNumber *tag2 = [NSNumber numberWithInt:[(UILabel*)b tag]];
            return [tag1 compare:tag2];
        }];
    
        return sortedArray;
    }
    

    Doing this, I can now access objects by using [resultRow1 objectAtIndex: i] or such. This saves overhead of having to iterate through and compare tags every time I need to access an element.

提交回复
热议问题