UILabel的可变IBOutlet名称? [英] Variable IBOutlet name for a UILabel?

查看:116
本文介绍了UILabel的可变IBOutlet名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

呃,在这里遇到麻烦...

Ugh, having some trouble here...

我在Interface Builder中有4个显示标签,在视图控制器中设置为IBOutlets。

I have 4 display labels in Interface Builder set up as IBOutlets in the view controller.

我用这些名字设置了它们
label1,label2,label3,label4

I've set them up with these names label1, label2, label3, label4

我想改变随机选择标签的标签文字

I'm want to change the label text for a randomly selected label

我正在尝试这个......

I'm trying this...

在头文件中我声明为属性:

In the header file I declare as a property:

@property (nonatomic retain) UILabel *myLabel;

然后在我的实现文件中我合成并且我正在尝试

And then in my implementation file I synthesize and I'm trying

myLabel = [UILabel valueForKey: [NSString stringWithFormat:@"label%d", randomInt]];

myLabel.text = @"bleh!";

myLabel = [UILabel ...行导致崩溃。有帮助吗?谢谢!

The myLabel = [UILabel ... line is causing to crash. Any help? Thanks!

推荐答案

你有正确的想法,但你应该传递 valueForKey:自我,而不是 UILabel ,假设其 self 拥有这些属性。

You have the right idea, but you should pass valueForKey: to self, not UILabel, assuming its self that owns these properties.

myLabel = [self valueForKey:[NSString stringWithFormat:@"label%d", randomInt]];

作为旁注,使用 IBOutletCollection可能更好。。在Xcode 4中,选择所有标签并将它们拖到头文件中。这将生成一个包含所有出口的 IBOutletCollection NSArray 。然后,您可以从该数组中选择一个随机索引。通常不幸的是 IBOutletCollection 以不确定的顺序存储其商店,但对于您的情况,它应该没问题。

As a side note, this is probably better done with an IBOutletCollection. In Xcode 4, select all of the labels and drag them to the header file. This will generate an IBOutletCollection NSArray containing all the outlets. You can then pick a random index from that array. It is usually unfortunate that IBOutletCollection stores its outlets in a non-deterministic order, but for your case it should be fine.

这篇关于UILabel的可变IBOutlet名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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