我可以将具有不同标签的多个对象连接到同一个IBOutlet吗? [英] Can I connect multiple objects with different tags to the same IBOutlet?

查看:120
本文介绍了我可以将具有不同标签的多个对象连接到同一个IBOutlet吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Interface Builder的一个视图中有30个按钮。每个都有100001和100030之间的不同标签。我发现每个按钮使用相同的动作很容易,按下每个按钮传递标签,并使用代码决定加载哪个级别。

I have 30 buttons in one view in Interface Builder. Each has a different tag between 100001 and 100030. I've found it easy to use the same action for each button, passing along the tag for each one when pressed and using code to decide which level to load.

我想将所有按钮连接到单个IBOutlet,但每个按钮根据用户保存的数据和按钮的标签加载不同的图像。

I want to connect all the buttons to a single IBOutlet, but have each button load a different image based on the user's saved data and the button's tag.

我该怎么做?

推荐答案

使用IBOutletCollection将一个插座集合添加到视图控制器,就像这样:

Use IBOutletCollection to add an outlet collection to your view controller, like this:

@property (retain, nonatomic) IBOutletCollection(UIButton) NSMutableSet* buttons;

这样您就可以将所有按钮连接到一个插座。属性按钮将是一个包含所有按钮的NSMutableSet。您可以使用按钮的标记属性继续识别单个按钮。如果你想遍历所有按钮,这可能很方便,也许是为了设置每个按钮的图像:

This will let you connect all your buttons to one outlet. The property buttons will be a NSMutableSet containing all your buttons. You can continue to identify individual buttons using the button's tag property. This is handy if you want to iterate through all your buttons, perhaps to set up each button's image:

for (UIButton *b in self.buttons) {
    b.imageView.image = [self imageForTag:b.tag];
}

(你需要提供 -imageForTag :为给定标签提供正确图像的方法,或者找到从标签映射到图像的其他方式。)

(You'll need to supply the -imageForTag: method to provide the right image for a given tag, or find some other way to map from tags to images.)

当然,如果您已经知道所有按钮的标记值范围,并且如果您已经注意在包含所有按钮的视图中使标记唯一,您也可以使用单独获取每个按钮 - viewWithTag:。这可能不像已经创建了整套按钮一样快,就像上面描述的插座集合一样,但它确实意味着维护的东西少了一些。

Of course, if you already know the range of tag values for all your buttons, and if you've taken care to make the tags unique inside the view containing all the buttons, you can also just fetch each button individually using -viewWithTag:. This is probably not as fast as having the whole set of buttons already created, as you have with the outlet collection described above, but it does mean that there's one less thing to maintain.

这篇关于我可以将具有不同标签的多个对象连接到同一个IBOutlet吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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