IBOutletCollection在Interface Builder中设置排序 [英] IBOutletCollection set ordering in Interface Builder

查看:152
本文介绍了IBOutletCollection在Interface Builder中设置排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用IBOutletCollections将几个类似UI元素的实例分组。特别是我将一些UIButton(类似于测验游戏中的蜂鸣器)和一组UILabel(显示得分)组合在一起。我想确保按钮上方的标签更新分数。我认为最容易通过索引访问它们。不幸的是,即使我以相同的顺序添加它们,它们并不总是具有相同的索引。 Interface Builder中是否有一种方法可以设置正确的顺序。

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.

推荐答案

编辑:几位评论者声称Xcode的更新版本按连接顺序返回 IBOutletCollections 。其他人声称这种方法在故事板中对他们不起作用。我自己没有对此进行测试,但如果您愿意依赖未记录的行为,那么您可能会发现我在下面提出的显式排序不再是必需的。

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.

不幸的是,似乎没有办法控制IB中 IBOutletCollection 的顺序,所以你' ll需要根据视图的某些属性对数组进行加载后对数组进行排序。您可以根据标记属性对视图进行排序,但在IB中手动设置标记可能相当繁琐。

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.

幸运的是,我们倾向于按照我们想要访问它们的顺序布置视图,因此通常基于x或y位置对数组进行排序就足够了:

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

这篇关于IBOutletCollection在Interface Builder中设置排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆